1

使用下面的代码循环出 200 个按钮,当行已满时,该行会下降一个档次。我猜一定有更好的方法,因为我的方法不起作用。

当第二行和第三行开始时,我只有一个按钮。没有错误,只是在最后一行上相互按纽。

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


    }

}

4

1 回答 1

0
  1. 当你想创建一个二维网格时,最好只使用嵌套循环而不是试图巧妙地使用单个循环。

  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];
        }
    }
}
于 2012-02-10T23:22:26.810 回答