Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change image tintColor in iOS and WatchKit

I have an UIImageView called "theImageView", with UIImage in a single color (transparent background) just like the left black heart below. How can I change the tint color of this image programmatically in iOS 7 or above, as per the tint method used in the iOS 7+ Navigation Bar icons?

Can this method also work in WatchKit for an Apple Watch app?

enter image description here

like image 376
chewy Avatar asked Oct 09 '13 14:10

chewy


People also ask

How do I change the color of a button image in Swift?

Set Image As Button's Background Color. Besides setting the button image icon, you can also set an image as the swift button's background color. To do this, just create a UIColor object use a selected UIImage object, then set the UIColor object as the button's backgroundColor property value.


1 Answers

iOS
For an iOS app, in Swift 3, 4 or 5:

theImageView.image = theImageView.image?.withRenderingMode(.alwaysTemplate) theImageView.tintColor = UIColor.red 

For Swift 2:

theImageView.image = theImageView.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) theImageView.tintColor = UIColor.redColor() 

Meanwhile, the modern Objective-C solution is:

theImageView.image = [theImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; [theImageView setTintColor:[UIColor redColor]]; 

Watchkit
In WatchKit for Apple Watch apps, you can set the tint color for a template image.

  1. You must add your image to an Asset Catalog in your WatchKit App, and set the image set to be rendered as a Template Image in the Attributes Inspector. Unlike for an iPhone app, you cannot set the template rendering in code in the WatchKit Extension at present.
  2. Set that image to be used in your WKInterfaceImage in interface builder for your app
  3. Create an IBOutlet in your WKInterfaceController for the WKInterfaceImage called 'theImage'...

To then set the tint color in Swift 3 or 4:

theImage.setTintColor(UIColor.red) 

Swift 2:

theImage.setTintColor(UIColor.redColor()) 

To then set the tint color in Objective-C:

[self.theImage setTintColor:[UIColor redColor]]; 

If you use a template image and do not apply a tint colour, the Global Tint for your WatchKit app will be applied. If you have not set a Global Tint, theImage will be tinted light blue by default when used as a template image.

like image 179
Duncan Babbage Avatar answered Oct 07 '22 19:10

Duncan Babbage