iosswiftuiimageview

Swift restore original image color after casting a tint


I have an image, inside a UIImageView, that comes with a default color, let's say a custom grey.
In my code at some point I set a different tint in this way

myImageView.image = myImageView.image!.withRenderingMode(.alwaysTemplate)
myImageView.tintColor = someCondition() ? UIColor.red : UIColor.lightGray

The fact is that I am not able to get back to the image's original grey color. My question is if there is a way to substitute the UIColor.lightGray part of my code with something telling the UIImageView not to use any tint, but its original color.


Solution

  • To not apply any tint you can set the image rendering mode like this:

    image.renderingMode = .alwaysOriginal
    

    In your code you could say:

    let renderingMode: UIImageRenderingMode = condition ? .alwaysTemplate : .alwaysOriginal
    myImageView.image = myImageView.image?.withRenderingMode(renderingMode)