在循环中并排创建UIButtons

时间:2011-11-09 23:30:00

标签: iphone objective-c ios ios4 uibutton

我正在尝试创建一个函数,每行显示三行三十个按钮。我的代码正确地在页面上创建了按钮,但我需要它们三个。

这是我的代码:

for (NSInteger index = 0; index < 90; index++)
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake((scrollView.frame.size.width / 2.0f) - 50.0f, 10.0f + (50.0f * (CGFloat)index), 100.0f, 30.0f);
    button.tag = index;
    [button setTitle:[NSString stringWithFormat:@"Button %ld", ((long)index + 1)] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(didTapButton:) forControlEvents:UIControlEventTouchUpInside];

    [zoomView addSubview:button];
}

1 个答案:

答案 0 :(得分:0)

所以,你可以在索引上使用整数除法和余数来调整框架:

for (NSInteger index = 0; index < 90; index++)
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake((scrollView.frame.size.width / 2.0f) - 170.0f+ (index % 3)*120.0f, 10.0f + (50.0f * (CGFloat)(index /3)), 100.0f, 30.0f);
    button.tag = index;
    [button setTitle:[NSString stringWithFormat:@"Button %ld", ((long)index + 1)] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(didTapButton:) forControlEvents:UIControlEventTouchUpInside];

    [zoomView addSubview:button];
}