单击第一个按钮时,它会突出显示,同时单击第二个,第二个突出显示并首先变为正常

时间:2015-03-19 10:37:01

标签: objective-c ios7 xcode5

我正在创建一个应用程序,其中包含五个按钮,以编程方式创建。以下是要求...

单击第一个按钮时,它会保持高亮显示。点击第二个按钮,首先变为正常,第二个保持高亮显示...即点击的特定按钮变为高亮显示,所有其他按钮保持正常.......请帮助..

3 个答案:

答案 0 :(得分:0)

这是我的解决方案:

获取属性以跟踪所选按钮

@property (nonatomic, weak) UIBUtton *lastSelectedButton;

在按钮回调方法中(添加按钮时配置的选择器):

- (void)didClickButton:(UIButton *)button {
    if (self.lastSelectedButton isEqual:button) {
        // Don't need to do anything in this case because the button is already selected
        return;
    }
    [self.lastSelectedButton setSelected:NO];
    [button setSelected:YES];
    [self setLastSelectedButton:button];
}

如果您有任何疑问或需要更多帮助,请与我联系!

答案 1 :(得分:0)

您可以创建一个包含标记值的实例变量int。现在哪个按钮单击,您需要清除上一个按钮的标签值并将其分配给当前按钮。

对于Ex:

int const TAG_HIGHLIGHTED_BUTTON = 100;

- (void)buttonAction:(UIButton *)button {
    UIButton *prevButton = [self.view viewWithTag:TAG_HIGHLIGHTED_BUTTON];
    [prevButton setTag:0];

    [button setTag:TAG_HIGHLIGHTED_BUTTON];
}

答案 2 :(得分:0)

您可以设置

[button setBackgroundImage:[UIImage imageNamed:@"normalbackgroundimage"] forState:UIControlStateNormal]; //not highlighted
[button setBackgroundImage:[UIImage imageNamed:@"highlightedbackgroundimage"] forState:UIControlStateHighlighted | UIControlStateSelected]; //highlighted

现在,当您设置button.selected = YES时,它会突出显示

所以你可以点击按钮

来做这样的事情
button1.selected = YES;
otherButton.selected = NO;

修改

您问题的简单解决方案是创建一个ibaction将其连接到您想要选择/取消选择的所有按钮,然后执行此操作

-(IBAction)someButtonPressed:(UIButton*)sender{
    button1.selected = NO;
    button2.selected = NO;
    button3.selected = NO; //and so on...just set all your buttons to selected = NO

    //at the end you just select button you clicked
    sender.selected = YES;
}