dynamic naming of UIButtons within a loop - objective-c, iphone sdk

Posted by von steiner on Stack Overflow See other posts from Stack Overflow or by von steiner
Published on 2010-05-13T21:26:29Z Indexed on 2010/05/13 21:54 UTC
Read the original article Hit count: 550

Filed under:
|
|
|
|

Dear Members, Scholars. 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;
    }


}

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about loop