4

I've added a PDF image as an asset to Xcode, I want to change the tintColor of the image but without any success.

I've tried to add User Defined Runtime Attributes, but it won't work.

Also tried to change programatically, but it won't work.

self.buttonBringFriend.imageView.tintColor = UIColor.white

Does anyone have a solution?

Xcode 11.1 Swift 5.1

ytpm
  • 4,962
  • 6
  • 56
  • 113

2 Answers2

7

To set image color, use the below method:

extension UIImageView {

    func setImageColor(color: UIColor) {
            let templateImage = self.image?.withRenderingMode(UIImage.RenderingMode.alwaysTemplate)
            self.image = templateImage
            self.tintColor = color
        }

    }

How to use:-

self.buttonBringFriend.imageView.setImageColor(color: .white)
pkc456
  • 8,350
  • 38
  • 53
  • 109
  • Works great, but when I click the image and it become highlighted, the color change back to the original color. – ytpm Oct 30 '19 at 20:18
  • @YossiTsafar On highlight, set the same image using this method. There are two ways of doing this: 1 )Subclass your button and call this method when highlighted. 2) Set the same highlighted image – pkc456 Oct 30 '19 at 20:21
  • tried that already, but it's not working. Do I call self.highlightedImage? – ytpm Oct 30 '19 at 20:24
  • @YossiTsafar, Yes, in the `setImageColor ` method, write this line: `self. highlightedImage = templateImage` – pkc456 Oct 30 '19 at 20:47
  • After setting the color, try to add this line: `buttonBringFriend.imageView?.highlightedImage = buttonBringFriend.imageView?.image` – pkc456 Oct 30 '19 at 21:03
6

Have you set Render As: Template Image in the Asset properties?

enter image description here

Derek Lee
  • 3,452
  • 3
  • 30
  • 39
Julian
  • 2,724
  • 1
  • 15
  • 21