0

I want to do a loop across every nine outlets (UIButton's, called btn1, btn2, btn3... btn9) that I have, like:

for(int i = 0; i < 9; i++) {
    [[btn(%@), i] setImage:someOne forState:UIControlStateNormal]; // I know that this is ridiculous, but it's just a way to demonstrate what I'm saying. :-)
}

Any tip?

Thanks a lot!

4 Answers4

2

You may want to check out IBOutletCollection (apple doc here) which allows you to connect multiple buttons to the same outlet and access them as you would a regular NSArray.

Sean
  • 5,810
  • 2
  • 33
  • 41
1

Have all the outlets you want to loop to loop through on a separate view.

for(int subviewIter=0;subviewIter<[view.subviews count];subviewIter++)
{
    UIbutton *button = (UIbutton*)[view.subviews objectAtIndex:subviewIter];
    // Do something with button.
}
Jaybit
  • 1,864
  • 1
  • 13
  • 20
  • Really cool, Jaybit! Thanks a lot for the other people, but the Jaybit answer is more simple and requires some code lines less. :-D –  May 11 '12 at 04:08
0

While creating UIButton, you can set tag property of button. Now there can be several ways of accessing that button, like one is -

NSArray *subViews = self.view.subviews;
for (int index = 0; index < [subViews count]; index++) {
    if ([subViews objectAtIndex:index] isKindOfClass:[UIButton Class]) {
    //Button is accessible now, Check for tag and set image accordingly.
    }
}
rishi
  • 11,779
  • 4
  • 40
  • 59
0

If you would like to do that you should think what congregates all the UIView instances or in your case: buttons. I would suggest you to add all the buttons to an array or any other kind of data format that helps you manage your objects.

Should you like to do that without using an external object for that purpose, I would suggest you to add all the buttons to a superview and then, you will be able to iterate over the subviews of the superview using: mySuperview.subviews property.

You could also give a unique ID number to each button (tag) right after when you initialize it, and then you can access tha button usIng the given tag:

myButton.tag = 1;
//Access the button using:
UIButton *b = (UIButton *) [superview viewWithTag:1];
Sagiftw
  • 1,658
  • 4
  • 21
  • 25