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?
Not sure if this sort of solves what you're after, or fits with your general development landscape but the first thing I would try would be to change the background colour of the button on the touchDown event.
Option 1:
You would need two events to be capture, UIControlEventTouchDown would be for when the user presses the button. UIControlEventTouchUpInside and UIControlEventTouchUpOutside will be for when they release the button to return it to the normal state
Option 2:
Return an image made from the highlight colour you want. This could also be a category.
and then change the highlighted state of the button:
You can subclass the UIButton and make a nice forState.
colourButton.h
colourButton.m
Notes (This is an example, I know there are problems and here are some)
I have used an NSMutableDictionay to store the UIColor for each State, I have to do a nasty text conversion for the Key as the UIControlState is not a nice straight Int. If it where you could init an Array with that many objects and use the State as an index.
Because of this you many have difficulties with e.g. a selected & disabled button, some more logic is needed.
Another problem is if you try and set multiple colours at the same time, I have not tried with a button but if you can do this it may not work
I have assumed this is StoryBoard, there is no init, initWithFrame so add them if you need them.
Subclass the UIButton and add inspectable properties for convenient use (written in Swift 3.0):
You can override
UIButton
'ssetHighlighted
method.Objective-C
Swift 3.0 and Swift 4.1
a more compact solution (based on @aleksejs-mjaliks answer):
Swift 3/4+:
Swift 2:
If you don't want to override, this is an updated version of @timur-bernikowich's answer (Swift 4.2):