关于UIButton选中和高亮状态下的图片切换

总结:当button的状态为selected的时候,高亮时对应的状态应该是selected|highlighted,这与normal下高亮的状态highlighted不同。

以下是stackover上的提问,附上:

I've a UIButton and I set it with:

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];

UIImage *imageNormal = [UIImage imageNamed:@"normal.png"];

UIImage *imageNormalHover = [UIImage imageNamed:@"normalHover.png"];

UIImage *imageSelected = [UIImage imageNamed:@"selected.png"];

UIImage *imageSelectedHover = [UIImage imageNamed:@"selectedHover.png"];

[myButton setImage:imageNormal forState:UIControlStateNormal];

[myButton setImage:imageSelected forState:UIControlStateSelected];

if (boolVar) {

[myButton setSelected:YES];

[myButton setImage:imageSelectedHover forState:UIControlStateHighlighted];

} else {

[myButton setImage:imageNormalHover forState:UIControlStateHighlighted];

}

The issue is when the state is normal and I try to press the button I see correctly the image normalHover.png but when the state is selected and I try to press the button I see still normalHover.png and not the selectedHover.png. It seems that with UIButton I'm unable to change the highlighted image. Do you how to solve?

Answer:

You need to set the image for the UIControlStateSelected | UIControlStateHighlighted combined state:

[myButton setImage:imageSelectedHover forState:(UIControlStateSelected | UIControlStateHighlighted)];

Because both states are on when the button is selected and you hignlight it by tapping on it.

(uibutton选中状态和高亮状态的区别:选中可以常态,高亮状态在Down才有效,up时候状态无效)----按下未抬起时为高亮状态

你可能感兴趣的:(关于UIButton选中和高亮状态下的图片切换)