9

我正在尝试在 WKWebView 上实现长按手势识别器,如下所示:

var webView: WKWebView?
let longPressRecognizer = UILongPressGestureRecognizer()

override func loadView() {
    super.loadView()

    var webViewConfig: WKWebViewConfiguration = WKWebViewConfiguration()
    webViewConfig.allowsInlineMediaPlayback = true
    webViewConfig.mediaPlaybackRequiresUserAction = false

    self.webView = WKWebView(frame: self.view.frame, configuration: webViewConfig)
    self.view = self.webView!

    //hook the long press event
    longPressRecognizer.addTarget(self, action: "onLongPress:")
    self.webView!.scrollView.addGestureRecognizer(longPressRecognizer)
}    

func onLongPress(gestureRecognizer:UIGestureRecognizer){
    NSLog("long press detected")

}

我没有收到错误,但我似乎无法让它触发 onLongPress 功能。

4

1 回答 1

18

您没有设置delegate手势识别器的。

//hook the long press event
longPressRecognizer.delegate = self
longPressRecognizer.addTarget(self, action: "onLongPress:")
self.webView!.scrollView.addGestureRecognizer(longPressRecognizer)

如果它仍然不起作用,这可能是由于WKWebView已经有自己的手势识别器。然后将以下方法添加到您的类中:

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

并在您的事件方法中检查手势是否开始:

func onLongPress(gestureRecognizer:UIGestureRecognizer){
    if gestureRecognizer.state == UIGestureRecognizerState.Began {
        NSLog("long press detected")
    }
}
于 2014-11-05T13:17:07.910 回答