Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select / deselect UIButton when tapped

I have a simple question which I cannot seem to find an answer for.

I have several UIButtons which are stored in an NSArray, with a for loop to set button.selected = YES when they are tapped. I need to deselect the same button when it is tapped, but I can't seem to find anything online to help. Here is my code:

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

Maybe this is not the best approach, sorry if I am missing something simple. I have tried adding else { button.selected = NO; but this only allows one button to be selected and deselects all others. Please can someone guide me in the right direction to deselect the current selected button when tapped.

like image 320
rosshump Avatar asked Sep 12 '14 11:09

rosshump


1 Answers

If you want to toggle between selected and unselected states each time you click on a UIButton instance, you can use the Objective-C code below:

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

Note that you can have the same result with an even shorter implementation:

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

With Swift 3, you would use the following code:

@IBAction func buttonPressed(_ sender: UIButton) {
    sender.isSelected = !sender.isSelected
}
like image 118
Imanou Petit Avatar answered Sep 28 '22 09:09

Imanou Petit