如何在iOS中使用for循环以编程方式添加UIButtons?

use*_*342 0 uibutton uiview ios

我想用for循环创建15个UIButtons.我想安排按钮,如矩阵,行和列,比如3行和5列.按钮高度为50,宽度为80.我可以设置y,宽度,高度坐标.但我只面对x坐标问题.告诉我设置x坐标的逻辑.

提前致谢.

βha*_*avḯ 5

    float x = 10;
    float y = 10;
    float width = 50;
    float height = 50;
    for(int i =0;i<15;i++)
    {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [btn setFrame:CGRectMake(x, y, width, height)];
        [btn setTitle:[NSString stringWithFormat:@"B%d",i+1] forState:UIControlStateNormal];
        [self.view addSubview:btn];

        x = x + width + 20;

        if((i+1)%3==0)
        {
            x = 10;
            y = y + height + 20;
        }
    }
Run Code Online (Sandbox Code Playgroud)

只需替换x和y,并在上面的代码中设置高度和宽度.