UIButton突出显示状态图像

时间:2011-10-02 22:32:00

标签: iphone objective-c cocoa-touch uibutton

我有UIButton,我将其设置为:

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];
}

问题是当状态正常并且我尝试按下按钮时我正确看到图像normalHover.png但是当状态被选中并且我尝试按下按钮时我仍然看到normalHover.png和不是selectedHover.png。似乎用UIButton我无法更改突出显示的图像。你怎么解决?

2 个答案:

答案 0 :(得分:5)

您需要为UIControlStateSelected | UIControlStateHighlighted组合状态设置图像:

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

因为当选择按钮时两个状态都打开,并且通过点击它来点亮它。

答案 1 :(得分:0)

在swift中,这是使用union

完成的
myButton.setImage(imageSelectedHover, forState: UIControlState.Selected.union(UIControlState.Highlighted))