Ad

Custom UIButton : How To Set Background Color On Selection Change?

- 1 answer

I have created a custom UIButton and I want its background to be red when selected, otherwise white.

So I tried this:

class MyCustomButton: UIButton {

    override var isSelected: Bool {
        didSet {
            backgroundColor = isSelected ? .red : .white
        }
    }

}

But it doesn't work, I've set a breakpoint but it never gets called. How can I do so? Thanks

Ad

Answer

How about :

override open var isHighlighted: Bool {
    didSet {
        backgroundColor = isHighlighted ? UIColor.red : UIColor.white
    }
}  

Note : The button type should be custom. It won't work on button with type system.

Ad
source: stackoverflow.com
Ad