user1388320
user1388320

Reputation:

Loop across all outlets

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!

Upvotes: 0

Views: 455

Answers (4)

Sagiftw
Sagiftw

Reputation: 1658

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

Upvotes: 0

rishi
rishi

Reputation: 11839

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.
    }
}

Upvotes: 0

Jaybit
Jaybit

Reputation: 1864

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.
}

Upvotes: 1

Sean
Sean

Reputation: 5820

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.

Upvotes: 2

Related Questions