jus*_*der 28 iphone xcode objective-c programmatically-created
我想以编程方式将多个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];
Run Code Online (Sandbox Code Playgroud)
复制/编辑此链接: 如何以编程方式创建基本UIButton?
但是如何在buttonClicked中确定:单击了哪个按钮?如果可能的话,我想传递标签数据来识别按钮.
Jas*_*oco 46
你可以在某个重要的地方(如数组)保持对实际按钮对象的引用,或者将按钮的标记设置为有用的东西(如某些其他数据数组中的偏移量).例如(使用标签,因为这通常必须有用):
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]);
}
Run Code Online (Sandbox Code Playgroud)
您可以为按钮指定标签.
button.tag = i;
Run Code Online (Sandbox Code Playgroud)
然后-buttonClicked:,检查发件人的标签:
-(void)buttonClicked:(UIButton*)sender {
int tag = sender.tag;
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
51359 次 |
| 最近记录: |