Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Background Color on UIButton when Disabled?

Is it possible to set the background color of a disabled UIButton? We'd like to use a more muted color when the button is disabled, but I do not see any methods within UIButton that would allow this. Is there a workaround or another way we could accomplish this?

like image 731
Shadowman Avatar asked Jun 09 '15 14:06

Shadowman


3 Answers

Seems that this is not possible as the background color property is controlled by the UIView class which is the parent of UIButton.

So UIButton control state doesn't own this property and doesn't control it.

But still you can inherit UIButton and overwrite the setEnabled method to update the color accordingly.

This is the most clear way to do it. as you can assign the inherited class to any UIButton in storyboard or Xib file. without the need for any connections. (no IBOutlets)

Hope this is helpful, if you wish I can share some code.

like image 97
Ahmad Al-Attal Avatar answered Sep 20 '22 21:09

Ahmad Al-Attal


I am concentrating on this comment of your's -"We'd like to use a more muted color when the button is disabled". If changing the alpha of the button is an acceptable solution you can very well use this code.

someButton.alpha  = 0.5;//This code should be written in the place where the button is disabled.
like image 36
GhostCode Avatar answered Sep 21 '22 21:09

GhostCode


The best way to work with button, in my honest opinion, is subclassing and customize UI, like in example:

class XYButton: UIButton {

    override public var isEnabled: Bool {
        didSet {
            if self.isEnabled {
                self.backgroundColor = self.backgroundColor?.withAlphaComponent(1.0)
            } else {
                self.backgroundColor = self.backgroundColor?.withAlphaComponent(0.5)
            }
        }
    }

}

Then you can use XYButton either in your storyboards/xibs or programmatically.

** more elegant:

didSet {
    self.backgroundColor = self.backgroundColor?.withAlphaComponent(isEnabled ? 1.0 : 0.5)
}
like image 39
Luca Davanzo Avatar answered Sep 18 '22 21:09

Luca Davanzo