如何向WKWebView

时间:2017-02-28 07:31:48

标签: ios swift uigesturerecognizer wkwebview

我需要将UIGestureRecognizer添加到WKWebView。

我将点按手势设置为WKWebView,它一直有效,直到网页视图加载网址。 加载网址后,它无法识别手势。

有什么方法可以为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")
    }

}

1 个答案:

答案 0 :(得分:13)

试试这个

class SwipeObserveExperimentController: UIViewController,UIGestureRecognizerDelegate

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

并调用以下方法

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

并将该函数调用为

 func viewTap {
    print("View Tap")
}