Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton Highlighted State not showing when clicking over a Selected UIButton

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];
like image 434
luca Avatar asked Jun 03 '13 22:06

luca


2 Answers

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)]
like image 120
Aaron Golden Avatar answered Nov 12 '22 16:11

Aaron Golden


In swift this would be:

button.setBackgroundImage(shadowImage, forState: UIControlState.Selected.union(UIControlState.Highlighted))
like image 5
Roland Keesom Avatar answered Nov 12 '22 16:11

Roland Keesom