在[UIButton addTarget]中传递自定义数据 [英] Passing custom data in [UIButton addTarget]

查看:520
本文介绍了在[UIButton addTarget]中传递自定义数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I add custom data while specifying a target in a UIButton?

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

我希望 buyButtonTapped 功能看起来像:

(void) buyButtonTapped: (UIButton *) button event: (id) event data: (id) data


推荐答案

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

not possible. the action that is triggered by an UIControl can have 3 different signatures.

- (void)action
- (void)action:(id)sender
- (void)action:(id)sender forEvent:(UIEvent *)event

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

None of them allows you to send custom data.

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

Depending on what you want to do you can access the data in different ways.

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

For example if the button is in a UITableView you could use something like this:

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

总有一种方法可以获得数据没有传递给按钮。

There is always a way to get the data without passing it to the button.

这篇关于在[UIButton addTarget]中传递自定义数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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