At some point in my app I have a highlighted UIButton
(for example when a user has his finger on the button) and I need to change the background color while the button is highlighted (so while the finger of the user is still on the button).
I tried the following:
_button.backgroundColor = [UIColor redColor];
But it is not working. The color remains the same. I tried the same piece of code when the button is not highlighted and it works fine. I also tried calling -setNeedsDisplay
after changing the color, it didn't have any effect.
How to force the button to change the background color?
To solve this problem I created a Category to handle
backgroundColor
States withUIButtons
:ButtonBackgroundColor-iOS
You can install the category as a pod.
Easy to use with Objective-C
Even more easy to use with Swift:
I recommend you import the pod with:
Using use_frameworks! in your Podfile makes easier to use your pods with Swift and objective-C.
IMPORTANT
I also wrote a Blog Post with more information.
An handy generic extension in Swift:
Swift 3.0
Use https://github.com/swordray/UIButtonSetBackgroundColorForState
Add to Podfile using CocoaPods
Swift
Objective-C
Here is the code in Swift to select for button state:
Example:
Here's an approach in Swift, using a UIButton extension to add an IBInspectable, called highlightedBackgroundColor. Similar to subclassing, without requiring a subclass.
I hope this helps.
In Swift you can override the accessor of the highlighted (or selected) property rather than overriding the setHighlighted method