0

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?

2 Answers 2

0

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;
Sign up to request clarification or add additional context in comments.

2 Comments

i see. so i need to create the buttons and put them inside array?
@AsiG You don't need to, but it's a best solution. Do not even keep them separate. If you have buttons button1, button2, button3, then you should have used an array.
0

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

7 Comments

thanks. but in your answer, what is the meaning of "int i = 1" if you're not using him in the code except "i++" ?
Please dont advise people to use tags. They are terrible for code quality.
@AsiG Just typical of a for loop haha! I will edit it out... but essentially I would use it for NSLogs... NSLog(@"Currently viewing button%i", i);
@Sulthan Seems very subjective... care to expand on why this is "terrible" for code "quality"? I find it a very simple method for beginners to wrap their minds around. Besides if tags were "terrible" why did Apple even create them?
@AlbertRenshaw First, not everything Apple does is good. The existence of API is not an argument. Tags introduce several bad concepts into your code. For beginners, they usually introduce "magic numbers". There are many other problems, including performance (searching instead of accessing directly) and uniqueness. However, the biggest problem is why you should even save something into an object when you can make a direct reference to it which is less confusing. There are some good uses of tags but they are rare.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.