以编程方式创建新的UIButton行

时间:2012-03-20 06:54:47

标签: iphone objective-c

目前我正在水平创建一行UIButton(0,1,2,3)

int x=0;

for (int i=0; i<4; i++) {

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(10+x,20, 100, 100);
    x=x+120;

    [btn.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:17.0]];
    btn.tag=i;
    NSString *str=[NSString stringWithFormat:@"%d",btn.tag];
    [btn setTitle:str forState:UIControlStateNormal];

    [btn setBackgroundColor:[UIColor redColor]];

    [self.view addSubview:btn];


}

但我想再次水平创建另一行按钮(4,5,6,7),但我无法找到执行此操作的逻辑。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

use like below

int x=0;
int y = 20;
for (int i=0; i<20; i++) //20 = total button
{
     UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
     btn.frame = CGRectMake(10+x,y, 100, 100);
     x=x+120;
     [self.view addSubview:btn];
    if((i+1)%4==0)//4 means how many buttons you need for a row
    {
        y+=110;
        x=0;
    }
 }