2010-05-13 65 views
0

因爲看起來很明顯我沒有武裝Objective C的知識。使用其他更簡單的計算機語言我試圖爲由簡單循環生成的按鈕列表設置一個動態名稱(如下面的代碼所示)。一個循環內的UIButtons的動態命名 - Objective-C,iphone sdk

簡單地說,我想有幾個動態生成的UIButton(在一個循環內)動態命名,以及其他相關的功能。

按鈕1,按鈕2,按鈕3等。

谷歌搜索和搜索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; 
    } 


} 

回答

2

哪裏出錯了,試圖在每次通過循環時爲按鈕想出不同的變量名稱。你不需要那樣做,它使事情變得比他們應該做的更難。如果你這樣做:

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

然後,你將有不同的按鈕,每次通過循環,因爲你需要。

+0

嘿格雷厄姆,謝謝你的答案。 我從來沒有想到它會如此簡單,你打開了我的思路,並讓我墜入愛河(甚至更多)Objective-C 謝謝。 – chewy 2010-05-13 21:55:59