5

I need to add UIGestureRecognizer to WKWebView.

I set tap gesture to WKWebView and it works until web view loads url. After url is loaded, it doesn't recognize the gesture.

Is there any way I can add gesture to WKWebView?

import UIKit
import WebKit

class SwipeObserveExperimentController: UIViewController {

    let webView: WKWebView = {
        let v = WKWebView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.scrollView.backgroundColor = .green
        return v
    }()


    override func viewDidLoad() {
        super.viewDidLoad()

        // Layout
        view.addSubview( webView )
        webView.translatesAutoresizingMaskIntoConstraints = false

        webView.topAnchor   .constraint(equalTo: view.topAnchor     ).isActive = true
        webView.bottomAnchor.constraint(equalTo: view.bottomAnchor  ).isActive = true
        webView.rightAnchor .constraint(equalTo: view.rightAnchor   ).isActive = true
        webView.leftAnchor  .constraint(equalTo: view.leftAnchor    ).isActive = true


        // Gesture
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(viewTap) )
        webView.addGestureRecognizer(tapGesture)


        // Load URL
        let url = URL(string: "http://www.akr-ski.com/")!
        let request = URLRequest(url: url)
        webView.load(request)
    }



    func viewTap(gesture: UITapGestureRecognizer) {
        print("View Tap")
    }

}
Bigair
  • 1,452
  • 3
  • 15
  • 42

1 Answers1

26

try this

class SwipeObserveExperimentController: UIViewController,UIGestureRecognizerDelegate

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(viewTap) )
tapGesture.delegate = self
webView.addGestureRecognizer(tapGesture)

and call the following method

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

and call the function as

func viewTap() {
  print("View Tap")
}
dimpiax
  • 12,093
  • 5
  • 62
  • 45
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
  • In Swift 4, the delegate method signature has changed. – user3246173 Jan 24 '18 at 19:48
  • 1
    Yup, it's `func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool` – Mr Rogers Oct 02 '18 at 21:18
  • 1
    @MrRogers - Thank you, I updated the answer – Anbu.Karthik Oct 03 '18 at 04:23
  • 1
    Basically, this solution works. However, links stopped working in my web page. Obviously, the tap event does not get though to WKWebView anymore. Has anyone an idea how to use two UITapGestureRecognizers at the same time (at the same touch)? – Lars Behnke Nov 07 '18 at 07:29
  • @Anbu.Karthik I have links in my WebView which stopped working, How can i have both Gesture and external link – Sivakrishna Perla Jan 13 '20 at 11:42