Color Tint UIButton Image
Solution 1:
As of iOS 7, there is a new method on UIImage
to specify the rendering mode. Using the rendering mode UIImageRenderingModeAlwaysTemplate
will allow the image color to be controlled by the button's tint color.
Objective-C
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *image = [[UIImage imageNamed:@"image_name"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[button setImage:image forState:UIControlStateNormal];
button.tintColor = [UIColor redColor];
Swift
let button = UIButton(type: .custom)
let image = UIImage(named: "image_name")?.withRenderingMode(.alwaysTemplate)
button.setImage(image, for: .normal)
button.tintColor = UIColor.red
Solution 2:
As Ric already mentioned in his post you can set the render mode in code, you can also do this directly in the image catalog, see attached image below. Just set the Render As
to Template Image
Caveat I have had problems with iOS 7 and this approach. So if you use iOS 7 as well you might want to do it in code as well to be sure, as described here.
Solution 3:
Custom Buttons appear in their respective image colors. Setting the button type to "System" in the storyboard (or to UIButtonTypeSystem
in code), will render the button's image with the default tint color.
(tested on iOS9, Xcode 7.3)
Solution 4:
You must set the image rendering mode to UIImageRenderingModeAlwaysTemplate
in order to have the tintColor
affect the UIImage. Here is the solution in Swift:
let image = UIImage(named: "image-name")
let button = UIButton()
button.setImage(image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), forState: .Normal)
button.tintColor = UIColor.whiteColor()
SWIFT 4x
button.setImage(image.withRenderingMode(UIImage.RenderingMode.alwaysTemplate), for: .normal)
button.tintColor = UIColor.blue
Solution 5:
If you have a custom button with a background image.You can set the tint color of your button and override the image with following .
In assets select the button background you want to set tint color.
In the attribute inspector of the image set the value render as to "Template Image"
Now whenever you setbutton.tintColor = UIColor.red
you button will be shown in red.