3

Hi I have an issue I can't figure out. I have wrote an extension that helps me colorize transparant PNG's

extension UIButton {
    func setImageColorForState(image: UIImage, color: UIColor, forState: UIControlState) {
        let temp = image.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
        setImage(temp, forState: forState)
        tintColor = color
    }
}

I use the extension as follows:

btn.setImageColorForState(originalImage!, color: UIColor.yellowColor(), forState: .Highlighted)
btn.setImageColorForState(originalImage!, color: UIColor.grayColor(), forState: .Normal)

Somehow it only takes the last state only. So in this case the highlight state is ignored. What am I missing here?

Reshad
  • 2,570
  • 8
  • 45
  • 86

3 Answers3

3

This can be done by subclassing UIButton and overriding the isHighlighted variable, similarly to the accepted answer here (https://stackoverflow.com/a/17602296/4673023).

    override open var isHighlighted: Bool {
        didSet {
            self.tintColor = isHighlighted ? UIColor.red : UIColor.gray
        }
    }

or, equivalently:

    override open var isHighlighted: Bool {
        didSet {
            if (isHighlighted) { self.tintColor = UIColor.red }
            else { self.tintColor = UIColor.gray }
        }

It's an old question, but I wrote this anyway in case someone incurs in something similar. Tested with Swift 3.2 and 4.0.


Although it's currently possible to skip the subclassing part and do the same with a UIButton extension, it shouldn't be done (https://docs.swift.org/swift-book/LanguageGuide/Extensions.html).

Martin
  • 684
  • 8
  • 12
0

Highlighted will be called just when you press, have you tried with selected state ? Also, you should set selected boolean to true.

Otherwise, it will simply return to normal state and hence, have gray color.

You can refer to this one as well : Keeping a UIButton selected after a touch

Community
  • 1
  • 1
Miknash
  • 7,888
  • 3
  • 34
  • 46
  • It doesn't have to stay selected. Just when I press it should change to yellow for a split second to show the user that its been clicked. – Reshad Nov 11 '15 at 09:30
0

I can't tell you a solution for what you are trying to do, but I can tell you whats wrong with your code:

Here you are setting the image for an state:

let temp = image.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
setImage(temp, forState: forState)

And here you are setting the TintColor. But the TintColor is not related to a specific state. It affects all states of the button.

tintColor = color

So if your are calling this...

btn.setImageColorForState(originalImage!, color: UIColor.yellowColor(), forState: .Highlighted)
btn.setImageColorForState(originalImage!, color: UIColor.grayColor(), forState: .Normal)

... you just override the TintColor.

Sry that I have no solution for your problem yet.

inf1783
  • 944
  • 11
  • 12