从UIWebView切换到WKWebView代理

时间:2016-05-12 17:37:31

标签: swift uiwebview wkwebview

相当于

的等价物
webView.delegate = self

是否在WKWebView中?我有

webView2.UIDelegate = self

但它不能按预期工作。

2 个答案:

答案 0 :(得分:5)

您可以使用键值观察来监控WKWebView的canGoBack和canGoForward。

SWIFT 3

向WKWebView添加两个键值观察器。

let webView = WKWebView(frame: view.frame)
view.addSubview(webView)

webView.addObserver(self, forKeyPath: #keyPath(WKWebView.canGoBack), options: .new, context: nil)
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.canGoForward), options: .new, context: nil)

现在,在视图控制器中实现observeValue(forKeyPath :)方法。

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

    if keyPath == #keyPath(WKWebView.canGoBack) || keyPath == #keyPath(WKWebView.canGoForward) {
        // Do Something...
    }
}

例如,您可以将这样的内容添加到按钮的更改色调颜色。

backButton.imageView?.tintColor = webView.canGoBack ? UIColor.blue : UIColor.gray
forwardButton.imageView?.tintColor = webView.canGoBack ? UIColor.blue : UIColor.gray

我通过阅读这里的文章找到了这种方法。

https://www.hackingwithswift.com/example-code/wkwebview/how-to-monitor-wkwebview-page-load-progress-using-key-value-observing

答案 1 :(得分:0)

您确定代码的only更改正在将UIWebView更改为WKWebView吗?我制作了一个示例项目,并且点按手势识别器适用于UIWebViewWKWebView。以下是相关代码:

class ViewController: UIViewController, UIGestureRecognizerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let webView = WKWebView(frame: view.frame)
        view.addSubview(webView)
        webView.translatesAutoresizingMaskIntoConstraints = false
        let urlString = "https://www.google.com"
        let url = NSURL(string: urlString)!
        let urlRequest = NSURLRequest(URL: url)
        webView.loadRequest(urlRequest)

        let recognizer = UITapGestureRecognizer(target: self, action: #selector(webViewTapped))
        recognizer.delegate = self
        webView.addGestureRecognizer(recognizer)
    }

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

    func webViewTapped(recognizer: UITapGestureRecognizer) {
        print("Tapped")
    }
}