How To Set UIButton Background Color For Disabled State
Now I can set using .disabled
Any Issue on UIButton?
UIButton basically does not have a built-in function to set its background for multiple state. Developers need an extra effort to make the disabled state to have a different background. In some cases, UIViewControllers might have different functions and approach to manage the background colour for .disabled
state (spaghetti code).
Solution
Here is the simple solution. A simple subclass of UIButton, to enable background changing based on isEnabled
value. So, whenever the value of isEnabled
is changed, it will reflect the background color. Awesome!
Please take note, this simple solution only will cover these two states; .normal and .disable state.
1) First, create a new class called “CustomButton” (you name it).
2) Add new enum to keep two different state.
3) Then, add two variables to keep two different background colors.
4) Override isEnabled
with didSet
closure to handle update on background
value to our defined colors.
5) Finally, add a custom function to set background color for both states .normal
and .disabled.
Great, the subclass is now ready! See the full code below.
Usage
How to use it? Well. Remember, first, set your button background using our custom function setBackgroundColor()
— in viewDidLoad
or using lazy var
closure.
Then, we can just set isEnabled
to true
or false
, it will update the background accordingly 🎉.
// set this in viewDidLoadbutton.setBackgroundColor(.blue, for: .normal)button.setBackgroundColor(UIColor.blue.withAlphaComponent(0.3), for: .disabled)// set enable or disable when neededbutton.isEnabled = true// button.isEnabled = false
Check the above quick preview extension for UIKit in my article here.
Thanks for your reading and don’t forget to share to you friends. Feedbacks are most welcome.
“Learn, that’s how we grow our coding skills”
References
https://developer.apple.com/documentation/uikit/uibutton?language=objc