【问题标题】:dynamic naming of UIButtons within a loop - objective-c, iphone sdk循环内UIButtons的动态命名-objective-c,iphone sdk
【发布时间】:2010-05-13 21:26:29
【问题描述】:

很明显,我没有掌握 Objective C 知识。利用其他更简单的计算机语言,我正在尝试为由简单循环生成的按钮列表设置动态名称(如以下代码所示)。

简单地说,我希望动态生成几个 UIButton(在一个循环中)动态命名它们,以及其他相关功能。

button1,button2,button3 等等。

在谷歌搜索 Stackoverlow 之后,我还没有得到一个明确简单的答案,因此我的问题。

- (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;
    }


}

【问题讨论】:

    标签: objective-c dynamic loops uibutton naming


    【解决方案1】:

    您出错的地方是每次通过循环时都试图为按钮提供不同的变量名称。您不需要这样做,这会使事情变得比应有的更难。如果你这样做:

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

    然后您将根据需要在每次循环中使用不同的按钮。

    【讨论】:

    • 嗨,格雷厄姆,非常感谢您的回答。没想到会这么简单,你打开了我的思路,让我(甚至更多)爱上了 Objective-C 谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    相关资源
    最近更新 更多