Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios8 gesture recognizer does not work on WKWebView with swift

i"m trying to implement a long press gesture recognizer on a WKWebView as follows:

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")

}

i don't get an error but i cant seem to make it trigger the onLongPress function.

like image 692
Gilad Avatar asked Nov 05 '14 11:11

Gilad


1 Answers

You didn't set the delegate of the gesture recognizer.

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

In case that it still doesn't work, this may probably due to WKWebView already has its own gesture recognizers. Then add the following method to your class:

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

And in your event method check for the gesture began:

func onLongPress(gestureRecognizer:UIGestureRecognizer){
    if gestureRecognizer.state == UIGestureRecognizerState.Began {
        NSLog("long press detected")
    }
}
like image 167
zisoft Avatar answered Oct 24 '22 06:10

zisoft