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?
Set Background Color on UIButton when Disabled?
23.7k views Asked by Shadowman AtThere are 6 answers
As suggested here:
https://stackoverflow.com/a/5725169/1586606
Set alpha property like;
myButton.alpha = 0.5
This code is for Swift 2
let rect = CGRectMake(0, 0, someButton.frame.width,someButton.frame.height)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColor(context, CGColorGetComponents(UIColor.lightGrayColor().CGColor))
CGContextFillRect(context, rect)
UIGraphicsBeginImageContextWithOptions(view.bounds.size, true, 0)
view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
someButton.setBackgroundImage(image, forState: .Disabled)
someButton.enabled = false
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.
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.
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)
}
Hope this helps :