以编程方式向视图添加多个按钮,调用相同的方法,确定它是哪个按钮 [英] Add a multiple buttons to a view programmatically, call the same method, determine which button it was

查看:126
本文介绍了以编程方式向视图添加多个按钮,调用相同的方法,确定它是哪个按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式将多个UIButtons添加到视图中 - 编译时按钮的数量是未知的。

I want to programmatically add multiple UIButtons to a view - the number of buttons is unknown at compile time.

我可以像这样制作一个或多个UIButton(在一个循环,但为简单而缩短):

I can make one or more UIButton's like so (in a loop, but shorted for simplicity):

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?

Copied/Edited from this link: How do I create a basic UIButton programmatically?

但是如何在buttonClicked中确定:单击了哪个按钮?如果可能的话,我想传递标签数据来识别按钮。

But how do I determine in buttonClicked: which button was clicked? I'd like to pass tag data if possible to identify the button.

推荐答案

您可以保留对实际按钮的引用某个重要的对象(如数组)或将按钮的标记设置为有用的东西(如某些其他数据数组中的偏移量)。例如(使用标签,因为这通常必须有用):

You could either keep a reference to the actual button object somewhere that mattered (like an array) or set the button's tag to something useful (like an offset in some other data array). For example (using the tag, since this is generally must useful):

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]);
}

这篇关于以编程方式向视图添加多个按钮,调用相同的方法,确定它是哪个按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆