0

As it may seem obvious I am not armed with Objective C knowledge. Levering on other more simple computer languages I am trying to set a dynamic name for a list of buttons generated by a simple loop (as the following code suggest).

Simply putting it, I would like to have several UIButtons generated dynamically (within a loop) naming them dynamically, as well as other related functions.

button1,button2,button3 etc..

After googling and searching Stackoverlow, I haven't arrived to a clear simple answer, thus my question.

- (void)viewDidLoad {
    // This is not Dynamic, Obviously 
    UIButton *button0 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button0 setTitle:@"Button0" forState:UIControlStateNormal];
    button0.tag = 0;
    button0.frame = CGRectMake(0.0, 0.0, 100.0, 100.0);
    button0.center = CGPointMake(160.0,50.0);
    [self.view addSubview:button0]; 
    // I can duplication the lines manually in terms of copy them over and over,  changing the name and other related functions, but it seems wrong. (I actually know its bad Karma)

    // The question at hand:
    // I would like to generate that within a loop
    // (The following code is wrong)

    float startPointY = 150.0;
    //
    for (int buttonsLoop = 1;buttonsLoop < 11;buttonsLoop++){

        NSString *tempButtonName = [NSString stringWithFormat:@"button%i",buttonsLoop];


        UIButton tempButtonName = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [tempButtonName setTitle:tempButtonName forState:UIControlStateNormal];
        tempButtonName.tag = tempButtonName;
        tempButtonName.frame = CGRectMake(0.0, 0.0, 100.0, 100.0);
        tempButtonName.center = CGPointMake(160.0,50.0+startPointY);
        [self.view addSubview:tempButtonName];
        startPointY += 100;
    }


}
chewy
  • 8,207
  • 6
  • 42
  • 70

1 Answers1

2

Where you're going wrong is in trying to come up with a different variable name for the button each time through the loop. You don't need to do that, and it makes things harder than they ought to be. If you do:

for(i=0;i<4;i++) {
    UIButton *button = //...

then you will have a different button each time through the loop as you require.

  • Hey Graham, Thank you kindly for the answer. I never expected it to be so simple, you opened my mind and made me fall in love (even more) with Objective-C Thank you. – chewy May 13 '10 at 21:55