【问题标题】:iOS Detect User Touch ReleaseiOS 检测用户触摸释放
【发布时间】:2011-09-11 18:31:37
【问题描述】:

这可能已经张贴在这里的某个地方,但我找不到它。我正在编写一个带有两个 UIView 的简单 iOS 应用程序。用户将首先按住屏幕的某个区域,然后松开对它的触摸,然后快速触摸下面的第二个视图。

第一个 UIView 附加了一个 UILongPressGestureRecognizer 并且工作正常。第二个 UIView 附加了一个 UITapGestureRecognizer 并且工作正常。但是,我无法让这些手势识别器中的任何一个返回任何表明用户释放触摸的内容。

我试过这段代码无济于事:

- (void)holdAction:(UILongPressGestureRecognizer *)holdRecognizer
{
    if (UIGestureRecognizerStateRecognized) {
        holdLabel.text = @"Holding Correctly. Release Touch when ready.";
        holdView.backgroundColor = [UIColor greenColor];
    } else if (UIGestureRecognizerStateCancelled){
        holdLabel.text = @"Ended";
        holdView.backgroundColor = [UIColor redColor];
}

任何建议都会很棒,尤其是如果有人知道如何实现返回用户触摸设备状态的调用。我查看了开发者文档,但发现是空的。

【问题讨论】:

  • 你能用按钮代替视图吗? UIButton 有一个 TouchUpInside 事件。

标签: ios uigesturerecognizer


【解决方案1】:

修补了几个小时后,我找到了一种可行的方法,但不确定它是否是最好的方法。原来我需要像下面的代码一样编写它。我没有调用我在 viewDidLoad() 方法中声明的特定 UIGestureRecognizer。

- (void)holdAction:(UILongPressGestureRecognizer *)holdRecognizer
{
    if (holdRecognizer.state == UIGestureRecognizerStateBegan) {
        holdLabel.text = @"Holding Correctly. Release when ready.";
        holdView.backgroundColor = [UIColor greenColor];
    } else if (holdRecognizer.state == UIGestureRecognizerStateEnded)
    {
        holdLabel.text = @"You let go!";
        holdView.backgroundColor = [UIColor redColor];
    }
}

【讨论】:

  • 很好的解决方案。我添加了[holdGesture setMinimumPressDuration:0.01]; 以使其更具响应性。
【解决方案2】:

您需要在此处使用手动触摸处理(而不是使用手势识别器)。任何 UIResponder 子类都可以实现以下四种方法:

– touchesBegan:withEvent:
– touchesMoved:withEvent:
– touchesEnded:withEvent:
– touchesCancelled:withEvent:

通过使用这些方法,您可以访问触摸事件的每个阶段。您可能必须实现自己的逻辑来检测长按,但您可以完全访问所有触摸。

有关触摸处理的更多信息,WWDC 2011 的这个会议是黄金(需要开发帐户):

https://developer.apple.com/itunes/?destination=adc.apple.com.8270634034.08270634040.8367260921?i=1527940296

【讨论】:

  • 我想观看会议,但链接已失效,如果您可以编辑它会很棒。谢谢
【解决方案3】:

Swift 4+

 let gesture = UILongPressGestureRecognizer(target: self, action:  #selector(self.checkAction))
    self.view.addGestureRecognizer(gesture)


     @objc func checkAction(sender : UILongPressGestureRecognizer) {
        if sender.state == .ended || sender.state == .cancelled || sender.state == .failed {

        }
    }

【讨论】:

    猜你喜欢
    • 2022-08-08
    • 2014-07-20
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多