UIButton Highlighted State not showing when clicking over a Selected UIButton
Asked Answered
J

4

10

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];
Justiciable answered 3/6, 2013 at 22:55 Comment(0)
C
21

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)]
Candlemaker answered 4/6, 2013 at 0:52 Comment(2)
Thanx God! haha ^^ I was going crazy. And thank you of course... I also tried that line of code but I was removing the line for the highlighted state as I thought was redundant :/Justiciable
It seems that even if you set background image for state selected and highlighted in IB,you get system highlighted image(dark gray) when adjustsImageWhenHighlighted is YES(default is YES) or normal image.So it is required to code Aaron Golden's answer.Groggery
N
5

In swift this would be:

button.setBackgroundImage(shadowImage, forState: UIControlState.Selected.union(UIControlState.Highlighted))
Narrative answered 5/10, 2015 at 12:34 Comment(0)
M
2

In Swift v3 (Nov. 2016):

button.setBackgroundImage(shadowImage, for: UIControlState.selected.union(UIControlState.highlighted))
Mousebird answered 16/11, 2016 at 13:10 Comment(0)
L
1

Swift 4.2

Applicable programmatically only.

aButton.setImage(UIImage(named: "your_image"), for: [.selected, .highlighted])
Laxative answered 12/2, 2019 at 7:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.