UIImage comes with property "renderingMode" from iOS 7 onwards. It can be set either 'alwaysTemplate' or 'alwaysOriginal'. This enum property helps us to re-use images that may thin your app size too.
As you can see in the result below, heart image turns red when liked and stays gray when disliked. In such cases only one image asset can be used.
Considering a UIButton object already created and added as a subview in the project, let's start with functionality. Again, I have only one image with name 'heart' in the asset folder (with gray fill). Using same image, I can create 2 instances of UIImage objects using rendering modes.
Now, set the images for selected and normal state.
Set the button tint color which will be rendered for Template mode. In our case, when user liked picture, button turns to red color.
Set target method for button event for example :
Also, in implement the button selection state toggle.
@objc func updatedButton(){
That's it. Now you can see the final result - When user selects the button, it turns red from template mode. When deselects, it turns back to original image.!
Let's get into to a real scenario !
I have added button as heart icon that gives like or dislike functionality for a picture.As you can see in the result below, heart image turns red when liked and stays gray when disliked. In such cases only one image asset can be used.
let notLikedImage = UIImage.init(named: "heart")?.withRenderingMode(.alwaysOriginal)
let likedImage = UIImage.init(named: "heart")?.withRenderingMode(.alwaysTemplate)
Now, set the images for selected and normal state.
self.likeButton.setImage(notLikedImage, for: .normal)
self.likeButton.setImage(likedImage, for: .selected)
self.likeButton.tintColor = .red
Set target method for button event for example :
self.likeButton.addTarget(self, action: #selector(updatedButton), for: .touchUpInside)
Also, in implement the button selection state toggle.
@objc func updatedButton(){
self.likeButton.isSelected = !self.likeButton.isSelected
}
That's it. Now you can see the final result - When user selects the button, it turns red from template mode. When deselects, it turns back to original image.!
Bonus tip :
Feels odd when button tapped it highlights? We can remove the button by setting 'false' to property 'adjustsImageWhenHighlighted'.
self.likeButton.adjustsImageWhenHighlighted = false