在[UIButton addTarget]中传递自定义数据

Gau*_*tam 21 iphone objective-c

如何在指定目标时添加自定义数据UIButton

id data = getSomeData();
[button addTarget:self 
           action:@selector(buyButtonTapped:event:) 
 forControlEvents:UIControlEventTouchUpInside];
Run Code Online (Sandbox Code Playgroud)

我希望buyButtonTapped函数看起来像:

(void) buyButtonTapped: (UIButton *) button event: (id) event data: (id) data
Run Code Online (Sandbox Code Playgroud)

Mat*_*uch 67

不可能.由UIControl触发的操作可以有3个不同的签名.

- (void)action
- (void)action:(id)sender
- (void)action:(id)sender forEvent:(UIEvent *)event
Run Code Online (Sandbox Code Playgroud)

它们都不允许您发送自定义数据.


根据您的要求,您可以通过不同方式访问数据.

例如,如果按钮位于UITableView中,您可以使用以下内容:

- (IBAction)buttonPressed:(UIButton *)sender {
    CGPoint buttonOriginInTableView = [sender convertPoint:CGPointZero toView:tableView];
    NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:buttonOriginInTableView];
    NSData *customData = [myDataSource customDataForIndexPath:indexPath];
    // do something
}
Run Code Online (Sandbox Code Playgroud)

始终有一种方法可以在不将数据传递给按钮的情况下获取数据.

  • 它始终是一个tableview ^^ (6认同)
  • 我是.随意挑战我.但我必须承认,有时它需要一些丑陋的变通方法或添加更多的实例变量. (3认同)

Ano*_*mie 21

您无法向操作方法发送额外数据.有许多方法可以将数据与按钮相关联,但除非数据是单个NSInteger,否则没有一种方法特别简单.

  • 您可以使用该tag属性来保存单个NSInteger.这可能就是您所需要的,或者您可以使用它来查找数组或字典中的对象.
  • 您可以将UIButton子类化以添加ivars/properties来存储所需的数据.
  • 您可以将其[NSValue valueWithNonretainedObject:button]用作字典的键.
  • 我个人最喜欢的一次性,您可以使用[关联引用]将数据对象与按钮相关联.

  • 子类化UIButton肯定是诀窍,应该是正确的答案imho之一 (4认同)