如何在UIGestureRecognizer initWithTarget操作中将参数传递给操作

时间:2012-06-21 23:47:12

标签: selector uitapgesturerecognizer

我正在使用以下代码

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(processTap)];

- (void) processTap
{
//do something
}

但我需要向processTap函数发送数据。反正有吗?

2 个答案:

答案 0 :(得分:30)

示例:

UIImageView *myPhoto = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"tab-me-plese.png"]];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(processTap:)];

[myPhoto setTag:1]; //set tag value
[myPhoto addGestureRecognizer:tap];
[myPhoto setUserInteractionEnabled:YES];

- (void)processTap:(UIGestureRecognizer *)sender
{
    NSLog(@"tabbed!!");
    NSLog(@"%d", sender.view.tag);    
}

答案 1 :(得分:3)

iOS - UITapGestureRecognizer - Selector with Arguments对类似问题有一个很好的答案,但是如果你想传递你不想附加到视图的数据,我建议创建第二个函数访问您需要的数据。例如:

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(passDataToProcessTap)];

- (void)passDataToProcessTap {
    [self processTapWithArgument:self.infoToPass];
    // Another option is to use a static variable,
    // Or if it's not dynamic data, you can just hard code it
}

- (void) processTapWithArgument:(id)argument {
    //do something
}