我的视图中有一个UI按钮
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 66, 29)];
[button setBackgroundImage:[UIImage imageNamed:@"filter_button_normal.png"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"filter_button_selected.png"] forState:UIControlStateHighlighted];
[button setBackgroundImage:[UIImage imageNamed:@"filter_button_down_selected.png"] forState:UIControlStateSelected];
[button addTarget:self action:@selector(filterAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
- (void)filterAction:(UIButton *)button
{
if(button.isSelected == YES)
{
[button setBackgroundImage:[UIImage imageNamed:@"filter_button_selected.png"] forState:UIControlStateHighlighted];
button.selected = NO;
}
else
{
#warning I want to change the UIButton Highlight Image, but without success
[button setBackgroundImage:[UIImage imageNamed:@"filter_button_down_normal.png"] forState:UIControlStateHighlighted];
button.selected = YES;
}
}
答案 0 :(得分:1)
如果您希望按钮的行为如下,
正常 - filter_button_normal
突出显示(按下按下按钮) - filter_button__down_selected
选中(从按钮移开触摸后) - filter_button_selected;
[button setBackgroundImage:[UIImage imageNamed:@"filter_button_normal.png"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"filter_button_selected.png"] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:@"filter_button_down_selected.png"] forState:UIControlStateHighlighted];
所以当用户触摸它时,图像会变为高亮显示,当他将手指移开时,它会变为选中状态
您添加的目标是UIControlEventTouchUpInside
[button addTarget:self action:@selector(filterAction:) forControlEvents:UIControlEventTouchUpInside];
所以在用户将手指从手指上移开后调用filterAction。
- (void)filterAction:(UIButton *)button
{
// the image will change automatically
if(button.isSelected == YES)
{
button.selected = NO;
}
else
{
button.selected = YES;
}
}