我想以编程方式将多个 UIButton 添加到视图中 - 按钮的数量在编译时未知。
我可以像这样制作一个或多个 UIButton(在循环中,但为了简单起见而缩短):
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(buttonClicked:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Button x" forState:UIControlStateNormal];
button.frame = CGRectMake(100.0, 100.0, 120.0, 50.0);
[view addSubview:button];
从此链接复制/编辑:如何以编程方式创建基本的 UIButton? https://stackoverflow.com/questions/1378765/how-do-i-create-a-basic-uibutton-programmatically
但是如何在buttonClicked:中确定单击了哪个按钮?如果可能的话,我想传递标签数据来识别按钮。
您可以在重要的地方保留对实际按钮对象的引用(例如数组),或者将按钮的标记设置为有用的内容(例如其他数据数组中的偏移量)。例如(使用标签,因为这通常很有用):
for( int i = 0; i < 5; i++ ) {
UIButton* aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton setTag:i];
[aButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[aView addSubview:aButton];
}
// then ...
- (void)buttonClicked:(UIButton*)button
{
NSLog(@"Button %ld clicked.", (long int)[button tag]);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)