Bigair Bigair -4 years ago 267
Swift Question

How to add gesture to WKWebView

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() {

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

// Load URL
let url = URL(string: "")!
let request = URLRequest(url: url)

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


Answer Source

try this

class SwipeObserveExperimentController: UIViewController,UIGestureRecognizerDelegate

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

and call the following method

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

and call the function as

 func viewTap {
    print("View Tap")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download