Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deselect all UIButtons when one is selected

I have eight (8) UIButtons setup in my game. When one is selected it shows that it is selected and if you click it again it will show as unselected. However, I want to make it so that when you select a button and any of the other seven (7) are selected, they become unselected.

I know how to do this through the use of [buttonName setSelected:NO] but the problem is I can't pass buttonOne to buttonTwo if buttonTwo has already been passed to buttonOne because I have already imported buttonTwo's header file in buttonOne. It throws a parse error if I have both headers importing each other. I've been stuck on this for a while now and was hoping that someone might have a solution to my problem.

Thanks for any help.

like image 320
John Snurr Avatar asked Sep 02 '13 13:09

John Snurr


People also ask

How do you select and unselect?

You can deselect any cells within the selected range with the Deselect Tool. Pressing the Ctrl key, you can click, or click-and-drag to deselect any cells or ranges within a selection. If you need to reselect any of those cells, continue holding the Ctrl key and reselect those cells (for Mac, use the Cmd key).


1 Answers

Get the parent view of the current button and iterate through all the buttons inside, unselecting all of them. Then, select the current one.

// Unselect all the buttons in the parent view
for (UIView *button in currentButton.superview.subviews) {
    if ([button isKindOfClass:[UIButton class]]) {
        [(UIButton *)button setSelected:NO];
    }
}

// Set the current button as the only selected one
[currentButton setSelected:YES];

Note: As suggested on the comments, you could keep an array of buttons and go over it the same way the above code does with the subviews of the parent view. This will improve the performance of your code in case the view containing the buttons has many other subviews inside.

like image 183
veducm Avatar answered Oct 10 '22 17:10

veducm