Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton tintColor for disabled and enabled state?

I have a custom class that inherits from UIButton. The thing that I want to accomplish is setting the tintColor property based on the button's enabled state (i.e enabled or disabled).

Is there any way to achieve that?

This is my class:

class ButtonsPostMenu: UIButton
{
    override func awakeFromNib()
    {
        titleLabel?.font = UIFont(name: Font_AvenirNext_Medium, size: 14)
        tintColor = UIColor.white
    }
}
like image 912
Dani Avatar asked Aug 23 '17 08:08

Dani


3 Answers

You could override the isEnabled property to achieve that. The tintColor will be automatically changed according to the button's isEnabled status:

class ButtonsPostMenu:UIButton {

    //......

    override var isEnabled: Bool {
        didSet{
            if self.isEnabled {
                self.tintColor = UIColor.white
            }
            else{
                self.tintColor = UIColor.gray
            }
        }
    }

    //......

}
like image 150
Yun CHEN Avatar answered Nov 16 '22 08:11

Yun CHEN


This is your class: Add changeStateOfButton custom method for manage tint color of UIButton

class ButtonsPostMenu: UIButton
{
    override func awakeFromNib()
    {
        titleLabel?.font = UIFont(name: Font_AvenirNext_Medium, size: 14)
        tintColor = UIColor.white
    }

    func changeStateOfButton() {
       if self.isEnabled {
           self.tintColor = UIColor.red // Set your color when button is enabled 
       }
       else {
           self.tintColor = UIColor.yellow // Set your color when button is disabled
       }
  }
}

And just call above method like when you want to set color based on enable/disable UIButton.

like image 38
Govaadiyo Avatar answered Nov 16 '22 09:11

Govaadiyo


You can attempt to replicate the setX(_ x: X, forState: State) API like this:

private class TintColorButton: UIButton {

    private var tintDict: [State.RawValue: UIColor] = [:]
    private var store: Set<AnyCancellable> = []

    override init(frame: CGRect) {
        super.init(frame: frame)

        publisher(for: \.isHighlighted).sink { [weak self] _ in self?.applyTintColor() }.store(in: &store)
        publisher(for: \.isEnabled).sink { [weak self] _ in self?.applyTintColor() }.store(in: &store)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setTintColor(_ color: UIColor?, forState state: State) {
        tintDict[state.rawValue] = color
        applyTintColor()
    }

    private func applyTintColor() {
        tintColor = tintDict[state.rawValue] ?? tintDict[State.normal.rawValue]
    }
}
like image 2
John Slade Avatar answered Nov 16 '22 10:11

John Slade