1
\$\begingroup\$

I am writing a control that has a toggle on (show/hide password). The UITextfield has a UIImageView in that acts as the toggle.

The question is, is it better to create the state images once and store them in the control, or to create them on demand?

Essentially this:

if let imageView = imgToggle {
    if self.isSecureTextEntry {
        imageView.image = UIImage(named: "eye.png")
    } else {
        imageView.image = UIImage(named: "no_eye.png")
    }
}

vs this:

private var showPassword: UIImage? = UIImage(named: "eye.png")
private var hidePassword: UIImage? = UIImage(named: "no_eye.png")

///...

if let imageView = imgToggle {
    if self.isSecureTextEntry {
        imageView.image = showPassword
    } else {
        imageView.image = hidePassword
    }
}

Is there any overhead in constantly recreating the image? How does that compare to storing the image in the control?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

There is no overhead in calling UIImage(named: ...) repeatedly, because the UIKit framework already caches the image, as documented in the UIImage(named:) reference:

This method looks in the system caches for an image object with the specified name and returns the variant of that image that is best suited for the main screen. If a matching image object is not already in the cache, this method locates and loads the image data from disk or from an available asset catalog, and then returns the resulting object.

So keep it simple and assign the image object where needed:

if self.isSecureTextEntry {
    imageView.image = UIImage(named: "eye.png")
} else {
    imageView.image = UIImage(named: "no_eye.png")
}

or shorter:

imageView.image = UIImage(named: isSecureTextEntry ? "eye.png" : "no_eye.png")

Note that self is not necessary to access instance members.

Or use image literals, a feature introduced in Xcode 8. You can simply type the name of an image resource in the asset catalog. This will be autocompleted to #imageLiteral(resourceName: "<name>"), but displayed as the image itself

enter image description here

in the Xcode source editor.

This is useful to avoid typing errors in the image name, and to visually check if the right image was chosen. You can even double-click on the image icon and choose a different one.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.