I have a simple question which I cannot seem to find an answer for.
I have several UIButton
s 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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With