自定义UIGestureRecognizer失败后,UIPinchGestureRecognizer不会触发

时间:2017-06-09 06:57:32

标签: ios swift uigesturerecognizer uipinchgesturerecognizer

我有一个自定义UIGestureRecognizer子类,可以检测特定类型的单指拖动。在同一个场景中,我还有一个UIPinchGestureRecognizer,可以检测到双指捏。

问题发生在用户进行捏合手势但是在另一个手指前放下一根手指时:自定义手势识别器看到一次触摸并且接合(将其状态设置为.began)并且捏合识别器不会“T。添加第二次触摸后,自定义识别器会注意到并将其状态切换为.failed。但是为时已晚,捏手势识别器无法捡起它。

以下是自定义UIGestureRecognizer子类的代码:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
    super.touchesBegan(touches, with: event)
    guard touches.count == 1 else {
        state = .failed
        return
    }
    state = .began
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
    super.touchesMoved(touches, with: event)
    guard touches.count == 1 else {
        state = .failed
        return
    }
    // do gesture recognizer stuff here
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
    super.touchesEnded(touches, with: event)
    state = .ended
}

我已尝试将cancelsTouchesInView设置为false并将delaysTouchesBegan设置为true以用于自定义手势识别器。这两种行为都没有区别。

当我使用UIPinchGestureRecognizerUIPanGestureRecognizer时,我没有这个问题,这让我觉得这不是预期的行为。

我的UIGestureRecognizer失败代码出了什么问题?我该如何修复它,以便UIPinchGestureRecognizer仍能识别触摸非同时开始的位置?

1 个答案:

答案 0 :(得分:0)

尝试使用UIGestureRecognizerDelegate协议来实施gestureRecognizer(_:shouldRecognizeSimultaneouslyWith:)。这可以让你同时识别两个手势。

class MyVC: UITableViewController, UIGestureRecognizerDelegate {

    override func viewDidLoad() {
        let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(handlePinchFrom))
        pinchGestureRecognizer.delegate = self
        view.addGestureRecognizer(pinchGestureRecognizer)
    }

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
}