使用Objective-C的for循环在屏幕上显示按钮

时间:2011-08-19 10:04:44

标签: objective-c ios xcode button for-loop

我有一个充满单词的数据库,每个单词都包含信息。我的工作是使用按钮在屏幕上显示单词,而不使用界面构建器。我想我可以使用for循环执行此操作,如下所示:

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

    UIButton *word= [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [word setTitle:@"Test" forState:UIControlStateNormal];
    [word setFrame:CGRectMake(0, 0, 100, 40)];
    [self.view addSubview:word];
}

这一切都在viewDidLoad部分完成。但是当我运行程序时,只显示一个按钮,那么如何让它显示所有20个按钮? 感谢正手, 尼古拉斯

4 个答案:

答案 0 :(得分:1)

可能有用。

for (int i=0; i <=20; i++) 
    { 
        UIButton *word= [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [word setTitle:@"Test" forState:UIControlStateNormal]; 
        [word setFrame:CGRectMake(0, (i+1)*100, 100, 40)]; 
        [self.view addSubview:word]; 
    }

答案 1 :(得分:0)

您应该动态更改添加的按钮的框架。以下代码水平放置视图。

float _width = 100;
float _x = i * _width;
[word setFrame:CGRectMake(_x, 100, _width, 40)];

答案 2 :(得分:0)

每次Button Frame都相似..所以只有1个按钮显示..

试试这个

[word setFrame:CGRectMake(0+i*110, 0+i*50, 100, 40)];

或根据需要设置框架

答案 3 :(得分:0)

你在这里做的是在同一帧上添加所有100个btns。而不是这个,如果你想在屏幕上显示所有100个btns,你将不得不使用两个for循环。

例如,如果你想在一行中显示四个bt,那么你应该使用,

 for(i = 0 ; i < 20 (i.e. no of elements in a single column) ; i++ )
 {
      for(j = 0; j < 4 (i.e. no of elements in a single row) ; j++)
      {
              UIButton *word= [UIButton buttonWithType:UIButtonTypeRoundedRect];
              [word setTitle:@"Test" forState:UIControlStateNormal]; 
              [word setFrame:CGRectMake(j*40, i*100, 100, 40)]; 
              [self.view addSubview:word]; 
      }
 }