WKWebView 键值监听 canGoBack与canGoForward动态设置按钮

最近项目中需要实现 WKWebView 的后退与前进功能。
经过实践,WKWebView 调用 goBack() 或 goForward() 方法并不会触发WKNavigationDelegate的任何代理方法。
偶然间在看到属性的注释:

@discussion @link WKWebView @/link is key-value observing (KVO) compliant
     for this property.

可以根据 canGoBack 和 canGoForward 属性设置 back 与 forward 按钮是否可用,所以采用键值监听的方式,同理 estimatedProgress、url等 也可以采用这种方式。这样就可以动态改变按钮的状态以及地址栏的地址了。
下面是代码片段:

...
// 创建WKWebView时设置,或者在viewDidLoad()中
webView.addObserver(self, forKeyPath: "title", options: .new, context: nil)
// 注意:url 属性对应的 keyPath 是大写的 URL
webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
// 注意:isLoading 属性对应的 keyPath 是 loading
webView.addObserver(self, forKeyPath: "loading", options: .new, context: nil)
webView.addObserver(self, forKeyPath: "canGoBack", options: .new, context: nil)
webView.addObserver(self, forKeyPath: "canGoForward", options: .new, context: nil)

...
// 在监听方法中设置 back 与 forward 按钮
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    guard let key = keyPath else { return }
    switch key {
    case "title":
    title = webView.title
    case "URL":
    urlInputOutlet.text = webView.url?.absoluteString
    case "loading":
    if webView.isLoading {
        stopButton.isEnabled = true
        refreshButton.isEnabled = false
    } else {
        stopButton.isEnabled = false
        refreshButton.isEnabled = true
    }
    case "canGoBack":
    backButton.isEnabled = webView.canGoBack
    case "canGoForward":
    forwardButton.isEnabled = webView.canGoForward
    default: break
    }
}
...
// 最后不要忘记移除监听
deinit {
    print("\(type(of: self)) deinited")
    webView.removeObserver(self, forKeyPath: "title")
    webView.removeObserver(self, forKeyPath: "URL")
    webView.removeObserver(self, forKeyPath: "loading")
    webView.removeObserver(self, forKeyPath: "canGoBack")
    webView.removeObserver(self, forKeyPath: "canGoForward")
}

你可能感兴趣的:(WKWebView 键值监听 canGoBack与canGoForward动态设置按钮)