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?
Override highlighted variable. Adding
@IBInspectable
makes you edit the highlighted backgroundColor in storyboard, which is nifty too.UIButton extension with Swift 3+ syntax:
Use it like:
Original Answer: https://stackoverflow.com/a/30604658/3659227
Try this if you have an image:
or see if
showsTouchWhenHighlighted
is enough for you.UPDATE:
Use the UIButtonBackgroundColor Swift library.
OLD:
Use the helpers below to create a 1 px x 1 px image with a grayscale fill color:
or an RGB fill color:
Then, use that
image
to set the button's background image:Helpers
Note:
ACU
is the class prefix of my Cocoa Touch Static Library called Acani Utilities, where AC is for Acani, and U is for Utilities.Below
UIIImage
extension will generates image object with specified color parameter.An example usage for a button can be applied for the button object as :
I have open-sourced a UIButton subclass, STAButton, to fill in this gaping functionality hole. Available under the MIT license. Works for iOS 7+ (I have not tested with older iOS versions).