【问题标题】:Getting the UIButton that was double-tapped from UIGestureRecognizer's action method获取从 UIGestureRecognizer 的操作方法中双击的 UIButton
【发布时间】:2016-02-18 19:36:38
【问题描述】:

我写了一个相当长的操作方法,连接到几个UIButtons,现在我意识到如果我点击其中一个按钮两次,我希望有一些不同的事情发生。所以我设置了两个手势识别器:

UITapGestureRecognizer *tapOnce = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(tapOnce:)];
UITapGestureRecognizer *tapTwice = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(tapTwice:)];


tapOnce.numberOfTapsRequired = 1;
tapTwice.numberOfTapsRequired = 2;

[tapOnce requireGestureRecognizerToFail:tapTwice];

[self.mybutton addGestureRecognizer:tapOnce];
[self.mybutton addGestureRecognizer:tapTwice];

然后,我实现方法:

- (void)tapOnce:(UIGestureRecognizer *)gesture{
   //Do what you were already doing
}


- (void)tapTwice:(UIGestureRecognizer *)gesture{ 
  // Some new functionality
}

现在,我对新功能没有任何问题。我被卡住的地方是试图让tapOnce: 方法来做我的按钮已经在做的事情。我需要知道点击了哪个按钮,所以我不能使用它:

[myButton sendActionsForControlEvents: UIControlEventTouchUpInside];

我也试过旧的:

for (button in myArrayOfButtons){
    [button sendActionsForControlEvents: UIControlEventTouchUpInside];
}

也没有运气。

然后我实际上创建了一个单独的方法来实现我的按钮,所以是什么:

- (IBAction)buttonPressed:(id)sender {

   //my functionality...
}

成为:

- (IBAction)buttonPressed:(id)sender {

    [self myMethodwithSender:sender];
}

-(void)myMethodwithSender: (id)sender{

    // my functionality
 }

所以这本身就起作用了,但是当我尝试一次又两次启动水龙头时,我就卡住了。我尝试将我的新方法放入一次点击的方法中:

- (void)tapOnce:(UIGestureRecognizer *)gesture{

       [self myMethodwithSender:sender];
}

当然,这个方法中没有发送者,所以它不起作用(对吧?)

然后我尝试改变这个:

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

到这里:

UITapGestureRecognizer *tapOnce = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(myMethodwithSender:)];

这也不起作用。所以我不知道该怎么做。欢迎提出任何建议。

【问题讨论】:

  • “它实际上是一组按钮”是什么意思,“也没有运气”到底是什么意思?发生了什么?
  • 在我的项目中有很多按钮,它们都被这个方法所吸引。然后,根据您按下的那个(因此“发送者”的重要性)出现不同的图像等等......当我尝试时: UIButton *button; for (button in self.allTheButtons){ [self myMethodwithSender:sender];} 在 tapOnce 方法中。我收到错误“使用未声明的标识符发件人。
  • 在这种情况下,Lou Franco 的答案正是您所需要的。

标签: objective-c cocoa-touch uibutton uitapgesturerecognizer sender


【解决方案1】:

与:

- (void)tapOnce:(UIGestureRecognizer *)gesture{
   [self myMethodwithSender:sender];
}

如果myMethodWithSender不使用sender,你可以发送nil。如果它需要它是按钮,gesture.view 应该是那个按钮(如果你将识别器附加到按钮上)

【讨论】:

  • 我刚刚尝试了gesture.view,它可以工作,但应用程序明显变慢(单击按钮时出现图像并且出现延迟?)
  • 只有稍等片刻才能知道第二次点击不会到来。在达到该超时之前,单击无法触发。
  • 我明白了。谢谢。既然我们在这里,任何想法为什么 UIButton *button; for (self.allTheButtons 中的按钮){ [button addGestureRecognizer:tapOnce]; [按钮 addGestureRecognizer:tapTwice];} 不起作用?
  • 每个按钮都需要一个新的手势识别器对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多