2

I'm having an issue with multiple UIButtons in a view. I'd like the buttons to be selected individually, with multiple selected at a time (example: 10 buttons, with buttons 1, 4, 5, 9 selected).

In my header I have a property for the IBOutletCollection:

@property (retain, nonatomic) IBOutletCollection(UIButton) NSMutableArray *buttonToStaySelected;

In my implementation, I have an IBAction:

-(IBAction)selectedButton:(id)sender{
  for (UIButton *b in self.buttonToStaySelected) {
     if (b.isSelected == 0){
        [b setSelected:YES];
  } else
        [b setSelected:NO];
  }
}

The issue I'm having is when I select any of the buttons tied to the collection, they all change to selected. I know the problem most likely (almost certain) lies in the loop, but every condition I've tried to stipulate breaks the code and leaves none of the buttons able to "change" state.

UPDATED

To have them selectable, change state and check off multiple, I used this as my final code:

-(IBAction)selectedButton:(id)sender {
  for (UIButton *b in self.buttonToStaySelected) {
      if (sender == b) {
      [b setSelected:!b.isSelected];
    }
   }
  }

Thanks for all the help!

hedrick
  • 211
  • 4
  • 13

1 Answers1

4

The selectButton: message is sent with an argument which specifies the button that was tapped, but you apply the action to all buttons in the collection, not just the button that was tapped.

-(IBAction)selectedButton:(id)sender
{
  for (UIButton *b in self.buttonToStaySelected)
  {
     if (sender == b)
     {
        b.isSelected == !b.isSelected
     }
  }
}
Jiri
  • 2,206
  • 1
  • 22
  • 19
  • That worked. It's only allowing the setSelected method to persist as long as another button is not selected. I'll fiddle around with it, but this is certainly more on track. – hedrick Jun 04 '12 at 21:31