Tom
Tom

Reputation: 197

Change tint color of disabled button won't work

I have a UIButton which is disabled. This UIButton has a image as an icon next to it. I reckon since it's disabled the tint color of the image is grey.

I've already tried to set the button in storyboard to custom and changed it tint color there, which didn't work.

I also tried the following code:

@IBOutlet weak var drivenKmDisplay: UIButton!

let color = UIColor(red: 0/255, green: 22/255, blue: 60/255, alpha: 1)

func setDrivenKm(drivenKm: Int) {
        drivenKmDisplay.isEnabled = false
        let string = String(drivenKm) + " km"
        drivenKmDisplay.setTitle(string, for: .disabled)

        let icon = UIImage(named: "timeline")!
        drivenKmDisplay.setImage(icon, for: .normal)
        drivenKmDisplay.imageView?.contentMode = .scaleAspectFit
        drivenKmDisplay.imageEdgeInsets = UIEdgeInsets(top: 0, left: -15, bottom: 0, right: 0)

        drivenKmDisplay.tintColor = color
    }

Upvotes: 1

Views: 1669

Answers (2)

After iOS 15, you can use UIButton.Configuration.attributedTitle and set the foreground color of the attributed string, like this:

    let button = UIButton()
    button.configurationUpdateHandler = { button in
        var config = button.configuration
        config?.attributedTitle = AttributedString(NSLocalizedString("Title", comment: ""),
                                                         attributes: AttributeContainer([NSAttributedString.Key.foregroundColor: button.isEnabled ? UIColor.white : UIColor.red]))
        button.configuration = config
    }

Upvotes: 1

gwyn
gwyn

Reputation: 63

You will have to subclass your button to change the tintColor when you enable/disable your button.

class MyButton: UIButton {
    override var isEnabled: Bool {
        didSet {
            tintColor = isEnabled ? .blue : .red
        }
    }
}

And to make sure the image in your button changes to your desired tint color, set the rendering mode of your image to alwaysTemplate. You can do this in code or in your Assets catalogue.

let icon = UIImage(named: "timeline")?.withRenderingMode(.alwaysTemplate)

You will also need to make sure your button doesn't adjust the image when it's disabled.

drivenKmDisplay.adjustsImageWhenDisabled = false

Upvotes: 3

Related Questions