我想以编程方式将多个 UIButton 添加到一个 View 中 - 按钮的数量在编译时是未知的。
我可以像这样制作一个或多个 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];
从这个链接复制/编辑: 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]);
}
关于iphone - 以编程方式向 View 添加多个按钮,调用相同的方法,确定它是哪个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2646297/