Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add gesture to WKWebView [duplicate]

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

}
like image 513
Bigair Avatar asked Nov 29 '22 13:11

Bigair


1 Answers

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")
}
like image 168
Anbu.Karthik Avatar answered Dec 01 '22 02:12

Anbu.Karthik