2012-02-10 70 views
1

使用下面的代碼循環200個按鈕,並在該行滿了時將該行下移一個缺口。 林猜測我必須有更好的方式,因爲我的方式劑量工作。Xcode:更改循環按鈕的行

當第二行和第三行開始時,我只有一個按鈕。沒有錯誤只是在最後一行上彼此按鈕。

-(void)viewDidLoad { 
int numba=0; 
int x=-20; 
int y=20; 

for(int i = 1; i <= 200; ++i) { 


    numba ++; 


    if (numba <16) { 

     x =x+20; 

    } else if (numba >16 && numba <26){ 
     x=-20; 
     x = x + 20; 
     y=40; 

    } else if (numba >26 && numba <36){ 
     x=-20; 
     x =x+20; 
     y=60; 

    } else { 
     x=-20; 
     x =x+20; 
     y=80; 
    } 



    UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    btn.frame = CGRectMake(x, y, 20, 20); 


    NSLog(@"numba = %d",numba); 
    NSLog(@"x = %d",x); 




    btn.tag = numba; 
    [btn setTitle:[NSString stringWithFormat: @"%d", numba] forState:UIControlStateNormal]; 

    [self.view addSubview:btn]; 


    } 

}

回答

0
  1. 當你想創建一個2維網格,最好只使用,而不是巧言令色帶有單環嵌套循環。

  2. 不要在您的代碼中撒上常數。您可以在方法或函數中定義符號常量。

以下是我會做:

- (void)viewDidLoad { 
    static const CGFloat ButtonWidth = 20; 
    static const CGFloat ButtonHeight = 20; 
    static const CGFloat RowWidth = 320; 

    int buttonNumber = 0; 

    for (CGFloat y = 0; buttonNumber < 200; y += ButtonHeight) { 
     for (CGFloat x = 0; buttonNumber < 200 && x + ButtonWidth <= RowWidth; x += ButtonWidth) { 
      ++buttonNumber; 
      UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
      button.frame = CGRectMake(x, y, ButtonWidth, ButtonHeight); 
      button.tag = buttonNumber; 
      [button setTtle:[NSString stringWithFormat:@"%d", buttonNumber] forState:UIControlStateNormal]; 
      [self.view addSubview:button]; 
     } 
    } 
}