我想以编程方式将多个UIButtons添加到视图中 – 编译时未知的按钮数.
我可以像这样制作一个或多个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中确定:单击了哪个按钮?如果可能的话,我想传递标签数据来识别按钮.
解决方法
@H_301_23@ 您可以在某个重要的位置(如数组)保持对实际按钮对象的引用,或者将按钮的标记设置为有用的东西(如某些其他数据数组中的偏移量).例如(使用标签,因为这通常必须有用):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]); }