UIButton Highlighted State not showing when clicking over a Selected UIButton

luca picture luca · Jun 4, 2013 · Viewed 14.1k times · Source

I want my UIButton to show up the highlighted state when I click over a button that is already selected.

Basically in the highlighted state I apply a *.png image as my UIButton backgroundImage to give a pressed down effect.

But if the button is already in the Selected State When I click over it again I just can't see the highlighted state but it goes straight to the normal state!

Watch the Issue--> Video of the Issue!

Help please

//0    init UIButton
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, aSide, aSide)];

//1    Give it a backgroundColor
[button setBackgroundColor:aColor];

[..]

//2    Set titleLabel and its style
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
[button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];

UIImage *shadowImage = [UIImage imageNamed:kBtnShadow];
shadowImage = [shadowImage stretchableImageWithLeftCapWidth:floorf(shadowImage.size.width/2) topCapHeight:floorf(shadowImage.size.height/2)];

[button setBackgroundImage:shadowImage forState: UIControlStateHighlighted];

[button setTitle:aLabel forState:  UIControlStateNormal];

//3    Assign tag and Action
[button setTag:tag];
[button addTarget:target action:a forControlEvents:UIControlEventTouchUpInside];

Answer

Aaron Golden picture Aaron Golden · Jun 4, 2013

The various states: UIControlStateNormal, UIControlStateSelected, and (UIControlStateSelected | UIControlStateHighlighted) are all actually distinct. If you want your shadowImage to apply both in the (only) highlighted state and in the highlighted+selected state, you must also set:

[button setBackgroundImage:shadowImage forState:(UIControlStateHighlighted | UIControlStateSelected)]