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];
luca
  • 36,606
  • 27
  • 86
  • 125

4 Answers4

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)]
Aaron Golden
  • 7,092
  • 1
  • 25
  • 31
  • 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 :/ – luca Jun 04 '13 at 06:28
  • 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. – tounaobun Feb 13 '15 at 08:01
5

In swift this would be:

button.setBackgroundImage(shadowImage, forState: UIControlState.Selected.union(UIControlState.Highlighted))
Roland Keesom
  • 8,180
  • 5
  • 45
  • 52
2

In Swift v3 (Nov. 2016):

button.setBackgroundImage(shadowImage, for: UIControlState.selected.union(UIControlState.highlighted))
ICL1901
  • 7,632
  • 14
  • 90
  • 138
1

Swift 4.2

Applicable programmatically only.

aButton.setImage(UIImage(named: "your_image"), for: [.selected, .highlighted])
Schiopu Evgheni
  • 549
  • 1
  • 4
  • 13