【发布时间】:2010-05-13 21:26:29
【问题描述】:
很明显,我没有掌握 Objective C 知识。利用其他更简单的计算机语言,我正在尝试为由简单循环生成的按钮列表设置动态名称(如以下代码所示)。
简单地说,我希望动态生成几个 UIButton(在一个循环中)动态命名它们,以及其他相关功能。
button1,button2,button3 等等。
在谷歌搜索 Stackoverlow 之后,我还没有得到一个明确简单的答案,因此我的问题。
- (void)viewDidLoad {
// This is not Dynamic, Obviously
UIButton *button0 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button0 setTitle:@"Button0" forState:UIControlStateNormal];
button0.tag = 0;
button0.frame = CGRectMake(0.0, 0.0, 100.0, 100.0);
button0.center = CGPointMake(160.0,50.0);
[self.view addSubview:button0];
// I can duplication the lines manually in terms of copy them over and over, changing the name and other related functions, but it seems wrong. (I actually know its bad Karma)
// The question at hand:
// I would like to generate that within a loop
// (The following code is wrong)
float startPointY = 150.0;
//
for (int buttonsLoop = 1;buttonsLoop < 11;buttonsLoop++){
NSString *tempButtonName = [NSString stringWithFormat:@"button%i",buttonsLoop];
UIButton tempButtonName = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[tempButtonName setTitle:tempButtonName forState:UIControlStateNormal];
tempButtonName.tag = tempButtonName;
tempButtonName.frame = CGRectMake(0.0, 0.0, 100.0, 100.0);
tempButtonName.center = CGPointMake(160.0,50.0+startPointY);
[self.view addSubview:tempButtonName];
startPointY += 100;
}
}
【问题讨论】:
标签: objective-c dynamic loops uibutton naming