I have a WKWebView that I would like to handle touches but I just can't find the right method.
webView is created programmatically in viewDidLoad, and loads fine.
override func viewDidLoad() {
super.viewDidLoad()
let site = "http://google.com"
let url = URL(string: site)
let request = URLRequest(url: url!)
webView = WKWebView(frame: self.view.frame)
webView.navigationDelegate = self
webView.uiDelegate = self // is this necessary for UITouch recognition?
webView.load(request)
self.view.addSubview(webView)
}
I've tried adding UITapGestureRecognizer in viewDidLoad... (per UIWebView and touch event)
override func viewDidLoad() {
//...
let taprecognizer = UITapGestureRecognizer(target: self, action: #selector(tapLocation))
taprecognizer.numberOfTapsRequired = 1
taprecognizer.delegate = self
webView.addGestureRecognizer(taprecognizer)
}
func tapLocation(recognizer: UITapGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
print("tapped")
return true
}
I've also tried getting touch from...
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("tapped")
}
My Debug View Hierarchy shows a bunch of WKCompositingViews which makes me think that these are using the touches before they can arrive to WKWebView or View.

I've added UIViewController, UIWebViewDelegate, WKNavigationDelegate, WKUIDelegate, UIGestureRecognizerDelegate to class...but it just won't go through.
Here is a sample working code in which i added WKWebView into main view and i am able to detect WKWebView touch event using UIGestureRecognizerDelegate
Swift4
//
// WebViewVC.swift
//
// Created by Test user on 01/02/18.
// Copyright © 2018 Test user. All rights reserved.
//
import UIKit
import WebKit
class WebViewVC: UIViewController,WKUIDelegate,UIGestureRecognizerDelegate {
var webView : WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let site = "http://google.com"
let url = URL(string: site)
let request = URLRequest(url: url!)
webView = WKWebView(frame: self.view.frame)
webView.uiDelegate = self // is this necessary for UITouch recognition?
webView.load(request)
self.view.addSubview(webView)
let taprecognizer = UITapGestureRecognizer(target: self, action: #selector(tapLocation))
taprecognizer.numberOfTapsRequired = 1
taprecognizer.numberOfTouchesRequired = 1
taprecognizer.delegate = self
webView.addGestureRecognizer(taprecognizer)
}
@objc func tapLocation(recognizer: UITapGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
print("tapped")
return true
}
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
print("Tap event will detect here.")
return true
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With