2012-02-10 71 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]; 
     } 
    } 
}