【问题标题】:How to detect tap begin with Long press?如何检测从长按开始的水龙头?
【发布时间】:2019-07-22 23:40:41
【问题描述】:

我想检测 3 个动作,“点击开始”、“长按开始”、“长按结束”。我想检测“点击开始”,无论检测长按(即每次触摸屏幕时,检测“点击开始”)并检测“点击开始”,然后检测“长按开始”以防继续触摸。

以下代码仅在未检测到“长按”的情况下才可以检测“轻按开始”。

    let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.Long(_:)))
    longPressGesture.minimumPressDuration = 3  
    longPressGesture.allowableMovement = 30    

    let shortPressGesture = UITapGestureRecognizer(target: self, action: #selector(self.Tap(_:)))

    touchView.addGestureRecognizer(shortPressGesture)
    touchView.addGestureRecognizer(longPressGesture)

}

@objc func Long(_ sender: UILongPressGestureRecognizer) {
    if(sender.state == UIGestureRecognizer.State.began) {
    print("Long tap begin")
    } else if (sender.state == UIGestureRecognizer.State.ended) {
    print("Long tap ended")
    }
}

@objc func Tap(_ sender: UITapGestureRecognizer) {
    print("Tap begin")
}

【问题讨论】:

  • 你不能在新闻发布时启动计时器并在发布时评估它吗?

标签: ios swift uitapgesturerecognizer


【解决方案1】:

你需要符合UIGestureRecognizerDelegate

class ViewController: UIViewController, UIGestureRecognizerDelegate

然后实现shouldRecognizeSimultaneouslyWith函数,让你的两个手势识别器同时工作。

另外,我认为您实际上想要使用两个 UILongPressGesutureRecognizer,因为在触摸时会检测到点击。

  @objc func Long(_ sender: UILongPressGestureRecognizer) {
    if(sender.state == UIGestureRecognizer.State.began) {
      print("Long tap begin")
    } else if (sender.state == UIGestureRecognizer.State.ended) {
      print("Long tap ended")
    }
  }

  @objc func Tap(_ sender: UILongPressGestureRecognizer) {
    if(sender.state == UIGestureRecognizer.State.began) {
      print("Tap begin")
    } else if (sender.state == UIGestureRecognizer.State.ended) {
      print("Tap ended")
    }
  }

  func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    if gestureRecognizer == longPressGesture && otherGestureRecognizer == shortPressGesture {
      return true
    }
    return false
  }

最后别忘了将手势识别器的代表设置为self

tapPressGesture.delegate = self
shortPressGesture.delegate = self

【讨论】:

    猜你喜欢
    • 2021-12-14
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    相关资源
    最近更新 更多