Mega Bundle SALE is ON! Get ALL of our amazing iOS app codebases at 80% OFF discount ūüĒ•

UIImage is the Swift approach to modeling images. In order to display an image on the screen, you’re most likely going to use UIImageView, which takes a UIImage object and presents it in the view hierarchy. To color UIImage objects there’s some extra work required. Coloring images can be very helpful when dealing with app icons, tab bar items, navigation items, etc.

The only way for a UIImage object to be colorable is to load it as a template. This can be done by specifying the rendering mode when initializing the UIImage object. If you’re setting the rendering mode to .alwaysTemplate, the image gets drawn by ignoring its color information. You can obtain the non-colored version of an image like this:

image = image.withRenderingMode(.alwaysTemplate)

Now, if you set this image as the source for a UIImageView component when setting the tintColor of the UIImageView, you’ll observe the image gets colored as desired. Check out a full example of how to color UIImage objects in Swift 4, inspired by our Restaurant App Template:

extension UIImage {
    static func localImage(_ name: String, template: Bool = false) -> UIImage {
        var image = UIImage(named: name)!
        if template {
            image = image.withRenderingMode(.alwaysTemplate)
        return image

let image = UIImage.localImage("cart-icon", template: true))
let imageView = UIImageView(image: image)
imageView.tintColor = .blue

In the example, we’ve also provided a UIImage extension, which contains a static method returning a UIImage object given the image name and whether it should render as a template or not. We recommend using this extension in your code, in order to avoid duplicating this operation in other places.

Notice that the other rendering mode available is .alwaysOriginal, which keeps the color information of the image and displays it as its original version. Keep in mind that abusing the use of .alwaysTemplate might result in performance penalties for your app since the operation of redrawing the image can be expensive.

Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping Cart