Asi G
Asi G

Reputation: 15

Objective C - running for loop on buttons name

if i have lets say 5 buttons named: "button1״ "button2״ "button3״ "button4״ "buttonn" and i want to run a for loop on their name like this: button[i].hidden = NO;

i know that button[i] will not work, its just for the example. what is the correct way to write it?

Upvotes: 0

Views: 556

Answers (2)

Albert Renshaw
Albert Renshaw

Reputation: 17902

You need to set a "tag" for each button.

button1.tag = 1;
button2.tag = 2;
button3.tag = 3;
button4.tag = 4;
button5.tag = 5;

then you can run your for-loop saying something like this:

for (UIButton *theButton in [viewContainingButtons subviews]) {
    if (theButton.tag == 1) {//change to any tag number
        NSLog(@"Variable `theButton` is currently `button1`");
        //do stuff to the first button using "theButton"
    }
}

Upvotes: 0

Sulthan
Sulthan

Reputation: 130162

If you have buttons named like that, you are doing it wrong. Whenever you have an index at the end of variable name, use an array. In this case a NSArray named buttons.

Iterating over the elements of an array is simple.

Also note that if you have created your buttons in the Interface Builder, you can use IBOutletCollection to connect your buttons into an array.

@property (nonatomic, strong) IBOutletCollection(UIButton) NSArray *buttons;

Upvotes: 0

Related Questions