点击时选择/取消选择UIButton

时间:2014-09-12 11:09:14

标签: ios objective-c uibutton xcode5

我有一个简单的问题,我似乎找不到答案。

我有几个UIButton存储在NSArray中,for循环在点击时设置button.selected = YES。我需要在点击时取消选择相同的按钮,但我似乎无法在网上找到任何帮助。这是我的代码:

- (IBAction)buttonPressed:(UIButton *)sender {
    NSArray *buttons = [NSArray arrayWithObjects:_asbBtn, _vwfBtn, _bpBtn, _rtaBtn, _mslmBtn, _pbaBtn, _rcfBtn, _mspBtn, _wpBtn, _aawBtn, _ppiBtn, _convBtn, nil];

    // Select buttons
    for (UIButton *button in buttons) {
        if (button == sender) {
            button.selected = YES;
        }
    }
}

也许这不是最好的方法,对不起,如果我遗漏了一些简单的话。我尝试添加else { button.selected = NO;但这只允许选择一个按钮并取消选择所有其他按钮。有人可以指导我正确的方向,在点击时取消选择当前选定的按钮。

5 个答案:

答案 0 :(得分:13)

如果要在每次单击UIButton实例时在选定的未选择的状态之间切换,可以使用下面的Objective-C代码:

- (IBAction) buttonPressed:(id)sender {
    if ([sender isSelected]) {
        [sender setSelected: NO];
    } else {
        [sender setSelected: YES];
    }
}

请注意,您可以使用更短的实现获得相同的结果:

- (IBAction) buttonPressed:(id)sender {
    [sender setSelected: ![sender isSelected]];
}

使用Swift 3,您将使用以下代码:

@IBAction func buttonPressed(_ sender: UIButton) {
    sender.isSelected = !sender.isSelected
}

答案 1 :(得分:3)

你为什么这样做呢?那太复杂了。简单的方法就是这样做

- (IBAction)reasonTapped:(id)sender 
{
    // Personal preference here but I would check to make sure
    // that the sender is actually a button.
    if([sender isKindOfClass:[UIButton class]]) {
        // Sender will be the button that is pressed.
        if([sender isSelected]) {
            // If already selected then set to selected to NO
            [sender setSelected:NO];
        } else {
            // Else set to selected to YES
            [sender setSelected:YES];
        } 
    } else {
        // Else if not an instance of UIButton throw some sort of warning.
    }
}

如果您在代码或界面/故事板中正确链接了所有按钮,当用户按下按钮时,它将调用此方法,sender将成为按下的按钮。所以在开始时不需要冗余阵列。

答案 2 :(得分:2)

使用此单个IBAction绑定所有按钮

- (IBAction)buttonPressed:(UIButton *)sender 
{
    if ([sender isSelected]) {
        [sender setSelected:NO];
    }
    else
    {
        [sender setSelected:YES];
    } 
}

答案 3 :(得分:1)

试试这段代码:

 -(IBAction)reasonTapped:(id)sender{
           if ([sender isSelected]) {
        [sender setSelected: NO];
    } else {
        [sender setSelected: YES];
    }
   }

答案 4 :(得分:1)

我找到了解决这个问题的简单方法。我的示例是2个按钮,但您可以轻松添加更多if语句以添加其他按钮。将所有按钮连接到.h文件作为属性并命名它们(我做了button1& button2)。将以下代码放在.m文件中并将其(通过故事板)连接到所有按钮。确保在设置按钮时为正常的UIControlStateNormal&设置图像。 UIControlStateSelected或这不会工作。

- (IBAction)selectedButton1:(id)sender {

if ([sender isSelected]) {
    [sender setSelected:NO];

    if (sender == self.button1) {
        [self.button2 setSelected:YES];
    }
    if (sender == self.button2) {
        [self.button1 setSelected:YES];
    }
}

else
{
    [sender setSelected:YES];

    if (sender == self.button1) {
        [self.button2 setSelected:NO];
    }
    if (sender == self.button2) {
        [self.button1 setSelected:NO];
    }

}