WKWebView提供了可以監(jiān)聽頁面加載進度,以及頁面的標題的方法。
let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight - navigationHeight ), configuration: WKWebViewConfiguration())
lazy private var progressView: UIProgressView = {
let progress = UIProgressView.init(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: UIScreen.main.bounds.width, height: 2))
progress.tintColor = UIColor.green
progress.trackTintColor = UIColor.white
return progress
}()
override func viewDidLoad() {
webView.addObserver(self, forKeyPath: "title", options: .new, context: nil)
webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
}
//添加觀察者方法
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
//設置進度條
if keyPath == "estimatedProgress"{
progressView.alpha = 1.0
progressView.setProgress(Float(webView.estimatedProgress), animated: true)
if webView.estimatedProgress >= 1.0 {
UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseOut, animations: {
self.progressView.alpha = 0
}, completion: { (finish) in
self.progressView.setProgress(0.0, animated: false)
})
}
}
//重設標題
else if keyPath == "title" {
self.title = self.webView.title
}
}