Change color of png in buttons - ios

I found the easiest approach below,

Open assetcatalog and select the image then go to attributes inspector and change Render As to Template Image as below

enter image description here

Then add below code in button Action method

yourButton.tintColor = .gray

Following code will set tint colour for normal state of button:

For Swift 4 and newer:

let origImage = UIImage(named: "imageName")
let tintedImage = origImage?.withRenderingMode(.alwaysTemplate)
btn.setImage(tintedImage, for: .normal)
btn.tintColor = .red

You can change tint colour according to your need when state changes for button.


Older versions

For Swift 3:

let origImage = UIImage(named: "imageName")
let tintedImage = origImage?.withRenderingMode(.alwaysTemplate)
btn.setImage(tintedImage, forState: .normal)
btn.tintColor = .redColor

For Swift 2: see revision history.

Tags:

Ios

Swift