UIScreenEdgePanGestureRecognizer 触发多次

UIScreenEdgePanGestureRecognizer is triggering multiple times

我使用以下代码在我的 WebView 中使用 UIScreenEdgePanGestureRecognizer 来回前进:

class FirstViewController: UIViewController {

        @IBOutlet var homewebview: UIWebView!

        // create left edge and right edge gesture
        let leftEdgePanGesture = UIScreenEdgePanGestureRecognizer()
        let rightEdgePanGesture = UIScreenEdgePanGestureRecognizer()


        override func viewDidLoad() {
            super.viewDidLoad()

            // add target for gesture
            self.leftEdgePanGesture.addTarget(self, action: #selector(FirstViewController.handleLeftEdge(_:)))
            self.rightEdgePanGesture.addTarget(self, action: #selector(FirstViewController.handleRightEdge(_:)))

            // set detection edge
            self.leftEdgePanGesture.edges = UIRectEdge.Left
            self.rightEdgePanGesture.edges = UIRectEdge.Right

            // add gesture into view
            self.view.addGestureRecognizer(self.leftEdgePanGesture)
            self.view.addGestureRecognizer(self.rightEdgePanGesture)
        }
        func handleLeftEdge( gesture: UIScreenEdgePanGestureRecognizer ) {
            homewebview.goBack()
        }

        // perform operation when right edge gesture detected
        func handleRightEdge( gesture: UIScreenEdgePanGestureRecognizer ) {
            homewebview.goForward()
        }
    }

我的问题是它触发了多次。它不会进入 back/forward 个网页,它会进入 back/forward ca。 5 个网页。

有什么解决办法吗?或者我必须使用 UISwipeGestureRecognizer。我不想使用 UISwipeGestureRecognizer,因为它不像 UIScreenEdgePanGestureRecognizer 那样可靠。 UISwipeGestureRecognizer 有时 "thinks" 我想在 WebView 中垂直滚动但没有反应。或者有解决办法吗?

只要状态发生变化,平移手势识别器就会调用处理程序方法。这包括它何时开始、结束以及其间的每一个动作。在处理程序内部,您需要检查手势识别器的状态并决定要做什么。

您希望每个手势仅触发一次代码,并且您希望仅在触摸移动超过阈值量时执行此操作。

class ViewController: UIViewController {

    let leftEdgePanGesture = UIScreenEdgePanGestureRecognizer()
    var leftPanTriggered: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()

        leftEdgePanGesture.addTarget(self, action: #selector(handleLeftEdge(_:)))
        leftEdgePanGesture.edges = .Left
        view.addGestureRecognizer(leftEdgePanGesture)
    }

    func handleLeftEdge(gesture: UIScreenEdgePanGestureRecognizer) {
        switch gesture.state {
            case .Began, .Changed:
                if !leftPanTriggered {
                    let threshold: CGFloat = 10  // you decide this
                    let translation = abs(gesture.translationInView(view).x)
                    if translation >= threshold  {
                        performLeftGesture()
                        leftPanTriggered = true
                    }
                }

            case .Ended, .Failed, .Cancelled:
                leftPanTriggered = false

            default: break
        }
    }

    func performLeftGesture() {
        homewebview.goBack()
    }

}