【问题标题】:How to pass argument to action in UIGestureRecognizer initWithTarget action如何在 UIGestureRecognizer initWithTarget 动作中将参数传递给动作
【发布时间】:2012-06-21 23:47:12
【问题描述】:

我正在使用下面的代码

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

- (void) processTap
{
//do something
}

但我需要向 processTap 函数发送数据。有没有办法做到这一点?

【问题讨论】:

标签: selector uitapgesturerecognizer


【解决方案1】:

示例:

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

【讨论】:

  • 欢迎来到 Stack Overflow!始终尝试为您的代码提供解释。
  • 如果您只需要出现手势的UIView,那么这是一个记录不充分但有效的答案。否则,您必须结合此响应:stackoverflow.com/questions/11594610/… from @nielsbot
  • 此标记对于传递 UserData 非常有用——无需进行繁琐的位置计算...
【解决方案2】:

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
}

【讨论】:

    猜你喜欢
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 2018-10-04
    • 1970-01-01
    相关资源
    最近更新 更多