[英]Showing buttons on the screen using a for-loop with Objective-C
我有一个充满单词的数据库,每个单词都包含信息。 我的工作是使用按钮在屏幕上显示单词,而不使用界面生成器。 我想我可以使用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个按钮呢? 正手感谢尼古拉斯
这可能很有用。
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];
}
您应该动态更改添加的按钮的框架。 以下代码将视图水平放置。
float _width = 100;
float _x = i * _width;
[word setFrame:CGRectMake(_x, 100, _width, 40)];
每次按钮框相似..所以只显示一个按钮..
这样尝试
[word setFrame:CGRectMake(0+i*110, 0+i*50, 100, 40)];
或根据您的需要设置框架
您在这里要做的是在同一帧上添加所有100个btns。 相反,如果要在屏幕上显示所有100个btn,则必须使用两个for循环。
例如,如果您想在一行中显示四个btns,则应使用,
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];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.