Domanda

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];
È stato utile?

Soluzione

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)]

Altri suggerimenti

In swift this would be:

button.setBackgroundImage(shadowImage, forState: UIControlState.Selected.union(UIControlState.Highlighted))

In Swift v3 (Nov. 2016):

button.setBackgroundImage(shadowImage, for: UIControlState.selected.union(UIControlState.highlighted))

Swift 4.2

Applicable programmatically only.

aButton.setImage(UIImage(named: "your_image"), for: [.selected, .highlighted])
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top