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?
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.
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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With