我想更改UIButton Highlight Image,但没有成功

时间:2014-01-20 08:44:47

标签: ios objective-c uibutton

我的视图中有一个UI按钮

我想更改UIButton精彩图像,但没有成功

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

1 个答案:

答案 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;
    }
}