Reputation: 12184
I have a UIButton , with 4 different states according to my app.
state-1 normal.
state-2 selected.
state-3 highlighted , going normal-to-selected.
state-4 highlighted , going selected-to-normal.
Initially button is in normal state, and when I press it it goes to selected state and keep toggling between these states.
this is achieved by specifying images for the two states and changing the selected property.
However, on change of every state I needed to change the highlighted state image to make sure it represents either of state 3 and state 4 while being pressed.
The problem is , while coming from selected to normal, it looks like there is not highlighted state for UIButton.
So for now I keep a BOOL ivar to check the selection state in my View. and keep the button in normal state and change its image for highlighted state and normal state with every action based on value of the BOOL ivar.
Is there any simpler way to achieve this ?
Upvotes: 1
Views: 1624
Reputation: 53880
Saving the highlighted state in a Boolean variable is a common way to keep track of the state, however here's something that will simply your code.
There is a setHighlighted
method that gets called on the UIControl that you can override. You can set your variable in there instead of in multiple actions:
-(void)setHighligted:(BOOL) highlighted {
self.mySavedHighlightedState = highlighted;
}
Create a custom UIButton class with a mySavedHighlightedState
property to implement this.
Upvotes: 0
Reputation: 22982
The reason for this is that the state is a mix of two values.
Some of the most commons ones
UIControlStateNormal,
UIControlStateHighlighted,
UIControlStateDisabled,
UIControlStateSelected,
UIControlStateSelected | UIControlStateHighlighted,
UIControlStateSelected | UIControlStateDisabled,
So if you want to have a highlighted
state when selected
then I prefer to do like this.
[button setImage:imageHighlighted forState:UIControlStateSelected | UIControlStateHighlighted];
If a general rule is that you always have same highlighted state when selected you can do something along the lines of
UIControlState mixedState = UIControlStateSelected | UIControlStateHighlighted;
[button setImage:[button imageForState:state] forState:state];
[button setBackgroundImage:[button backgroundImageForState:state] forState:state];
[button setTitleColor:[button titleColorForState:state] forState:state];
And so on
Upvotes: 8