6

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.

3
  • Wow, hold a second, why on Earth do you import custom buttons header files to each other? And don't tell me you have created a custom class for each and every UIButton you have. Sep 2, 2013 at 13:19
  • Before selecting any button, recreate all buttons Sep 2, 2013 at 13:28
  • Please, select an answer if any of them helped you at all or provide more details to see if we can help you. Thanks!
    – veducm
    Sep 4, 2013 at 16:03

10 Answers 10

12

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.

2
  • 1
    You can skip checking the currentButton with each button simply by changing the order of operations. First — deselect all, than select current. And it is better to create separated array for buttons that following this behavior, than iterating through all subviews.
    – ArtFeel
    Sep 2, 2013 at 13:58
  • @ArtFeel You are right. We could just deselect all the buttons first and select the current one afterwards. I will edit the answer. Thanks!!
    – veducm
    Sep 2, 2013 at 14:08
2

I know its too late to answer this question but I did it in only small lines of code . Here is what i did :

NSArray *arrView = self.view.subviews;
    for (UIButton *button in arrView) {
        if ([button isKindOfClass:[UIButton class]]) {
            [((UIButton *) button) setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
    }
[button1 setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
2

Simple way to do.

-(void)buttonSelected:(id)sender{
    UIButton *currentButton = (UIButton *)sender;
    for(UIView *view in self.view.subviews){

        if([view isKindOfClass:[UIButton class]]){

            UIButton *btn = (UIButton *)view;
            [btn setSelected:NO];
        }
    }

    [currentButton setSelected:YES];

}
1

I actually created an answer by reading all of your guys input, which I thank you greatly for. The tag property of the UIButton class was unknown to me before this post.

I created own subclass of UIButton, let's call it CustomUIButton.m. I created a NSMutableArray property for use when storing the buttons, which I'll call customButtonArray.

When I created the button, I set the tag property, and added the button to a local array on the parent view controller. After all buttons I wanted were created, I set the customButtonArray, like so:

// Initialize buttonHolderArray
NSMutableArray *buttonHolderArray = [[NSMutableArray alloc] init];

// Create a button
CustomUIButton *newButton = [[CustomUIButton alloc] initWithFrame:CGRectMake(10, 10, 50, 30)];
newButton.tag = 1;
[newButton setImage:[UIImage imageNamed:@"newButtonUnselected" forControlState:UIControlStateNormal]];
[buttonHolderArray addObject:newButton];

// Create additional buttons and add to buttonHolderArray...
// using different numbers for their tags (i.e. 2, 3, 4, etc)

// Set customButtonArray property by iterating through buttonHolderArray
NSInteger buttonCount = [buttonHolderArray count];

for (int i = 0; i < buttonCount; i++)
{
   [[buttonHolderArray objectAtIndex:i] setCustomButtonArray:buttonHolderArray];
}

To deselect any other button selected when a different buttons handleTap: is called, I iterated through the customButtonArray in the subclass main file and set the selected property to NO. I also set the correct image from another array property that I manually populated with the images, which I did so the array didn't have to be populated every time a button was pressed. At the end, unselected all other buttons, like so:

// Populate two arrays: one with selected button images and the other with
// unselected button images that correspond to the buttons index in the 
// customButtonArray
NSMutableArray *tempSelectedArray = [[NSMutableArray alloc] init];
[tempSelectedArray addObject:[UIImage imageNamed:@"newButtonSelected"]];
// Add the other selected button images...
// Set the property array with this array
[self setSelectedImagesArray:tempSelectedArray];

NSMutableArray *tempUnselectedArray = [[NSMutableArray alloc] init];
[tempUnselectedArray addObject:[UIImage imageNamed:@"newButtonUnselected"]];
// Add the other unselected button images...
// Set the property array with this array
[self setUnselectedImagesArray:tempUnselectedArray];

- (void)handleTap:(UIGestureRecognizer *)selector
{
    // Get the count of buttons stored in the customButtonArray, use an if-elseif
    // statement to check if the button is already selected or not, and iterate through
    // the customButtonArray to find the button and set its properties
    NSInteger buttonCount = [[self customButtonArray] count];

    if (self.selected == YES)
    {
        for (int i = 0; i < buttonCount; i++)
        {
            if (self.tag == i)
            {
                [self setSelected:NO];
                [self setImage:[[self unselectedImagesArray] objectAtIndex:i] forControlState:UIControlStateNormal];
            }
        }
    }
    else if (self.selected == NO)
    {
        for (int i = 0; i < buttonCount; i++)
        {
            if (self.tag == i)
            {
                [self setSelected:NO];
                [self setImage:[[self selectedImagesArray] objectAtIndex:i] forControlState:UIControlStateNormal];
            }
        }
    }

    for (int i = 0; i < buttonCount; i++)
    {
        if (self.tag != i)
        {
            [self setSelected:NO];
            [self setImage:[[self unselectedImagesArray] objectAtIndex:i] forControlState:UIControlStateNormal];
        }
    }
}

Thanks for all of the useful information though, figured I should share the final answer I came up with in detail to help anyone else that comes across this problem.

1

I figured out a pretty easy way to solve this. My example is for 2 buttons but you can easily add more if statements for additional buttons. Connect all buttons to the .h file as properties and name them (I did button1 & button2). Place the following code in your .m file and Connect it (via the storyboard) to all of your buttons. Make sure when you are setting up your button to set an image for BOTH the normal UIControlStateNormal & UIControlStateSelected or this wont work.

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

}
0

To answer "It throws a parse error if I have both headers importing each other"...

You should refrain from using #import in .h files as much as possible and instead declare whatever you're wanting to use as a forward class declaration:

@class MyCustomClass

@interface SomethingThatUsesMyCustomClass : UIViewController

@property (nonatomic, strong) MyCustomClass *mcc;

@end

Then #import the header in your .m file:

#import "MyCustomClass.h"

@implementation SomethingThatUsesMyCustomClass

-(MyCustomClass *)mcc
{
   // whatever
}

@end

This approach will prevent errors caused by #import cycles.

Though I must say I agree with SergiusGee's comment on the question that this setup feels a bit strange.

0

The easiest approach here would be to get the parent UIView the buttons are on and iterate through it. Here's a quick example from my code:

for (UIView *tmpButton in bottomBar.subviews)
{
  if ([tmpButton isKindOfClass:[UIButton class]])
  {
       if (tmpButton.tag == 100800)
       {
           tmpButton.selected = YES;
           [tmpButton setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
           [tmpButton setTitleColor:[UIColor greenColor] forState:UIControlStateHighlighted];

       }else{

          tmpButton.selected = NO;
          [tmpButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
          [tmpButton setTitleColor:[UIColor redColor]  forState:UIControlStateHighlighted];
        }
    }
}
5
  • Wouldn't it be simpler to use the 'UIControlStateSelected' only at UIButtons instanciation ? setting UIControlStateNormal as redColor, and UIControlStateSelected as greenColor ? This way, you don't have to change buttons color each time user touches the UI.
    – Vinzzz
    Sep 2, 2013 at 13:26
  • What happens to this code if bottomBar has subviews which aren't UIButtons ?
    – Vinzzz
    Sep 2, 2013 at 13:28
  • @Vinzzz what I'm doing here is making the touch of the buttons non-visible to the user. What happens? My guess that it doesn't get executed. We could change the UIButton in the for statement to a simple UIView if you'd like it more. Sep 2, 2013 at 13:30
  • 1
    I think you guess wrong, and you would get a runtime error. Changing UIButton for a UIView, then checking [view isKindOf:[UIButton class]] might be more error-prone, IMHO.
    – Vinzzz
    Sep 2, 2013 at 13:32
  • @Vinzzz agree. Changed just in case. Sep 2, 2013 at 13:33
0

Did you try using ReactiveCocoa framework and add some blocks for your code , this is not the most simple approach yet i would say it is the most effective when you have multiple dependencies and very good for scaling

I have created a small project for a solution to your problem using my suggested approach (I tried to adapt it to the good old MVC pattern instead of my preferred MVVM)

you can find it here

https://github.com/MWaly/MWButtonExamples

make sure to install cocoa pods file as we need "ReactiveCocoa" and "BlocksKit" for this sample

we will use two main classes

ViewController => The viewController object displaying the buttons MWCustomButton => Custom UIButton which handles events

when creating the buttons a weak reference to the viewController is also created using the property

@property (weak) ViewController *ownerViewController ;

events will be handled using the help of blocksKit bk_addEventHandler method and pass it to the block of the ViewController (selectedButtonCallBackBlock)

 [button bk_addEventHandler:^(id sender)
    {
        self.selectedButtonCallBackBlock(button);

    } forControlEvents:UIControlEventTouchUpInside];

now in the ViewController for each button touched the callBackButtonBlock will be trigerred , where it will change its currently selected button if applicable

__weak __typeof__(self) weakSelf = self;

self.selectedButtonCallBackBlock=^(MWCustomButton* button){
     __typeof__(self) strongSelf = weakSelf;
    strongSelf.currentSelectedButton=button;
      };

in the MWCustomButton class , it would listen for any changes in the property of "currentSelectedButton" of its ownerViewController and will change its selection property according to it using our good Reactive Cocoa

 ///Observing changes to the selected button
    [[RACObserve(self, ownerViewController.currentSelectedButton) distinctUntilChanged] subscribeNext:^(MWCustomButton *x) {
            self.selected=(self==x);
    }];

i think this would solve your problem , again your question might be solved in a simpler way , however i believe using this approach would be more scalable and cleaner.

0

Loop through all views in parent view. Check if it is a UIButton(or your custom button class) and not the sender. Set all views isSelected to false. Once loop is finished, set sender button isSelected to true.

Swift 3 way:

func buttonPressed(sender: UIButton) {
    for view in view.subviews {
        if view is UIButton && view != sender {
            (view as! UIButton).isSelected = false
        }
    }
    sender.isSelected = true
}
0

Swift 4

  //Deselect all tip buttons via IBOutlets

  button1.isSelected = false
  button2.isSelected = false
  button3.isSelected = false

  //Make the button that triggered the IBAction selected.
  sender.isSelected = true

  //Get the current title of the button that was pressed.
    let buttonTitle = sender.currentTitle!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.