在WKWebView上添加進度條比在UIWebView上簡單了許多,並且是真的進度了,不用再自己去算比例或者造假的進度條了,
廢話少說,進入正題吧:
首先WKWebView有個屬性 UIProgressView
1 /** 進度條 */ 2 var progressView : UIProgressView? = nil 3 let keyPathForProgress : String = "estimatedProgress"
1 override func viewDidLoad() { 2 super.viewDidLoad() 3 4 initWebView() 5 initProgressView() 6 }
1 override func viewWillLayoutSubviews() { 2 let width = self.view.bounds.size.width; 3 let height = self.view.bounds.size.height; 4 let statusBarBounds = UIApplication.sharedApplication().statusBarFrame 5 6 let webViewHeight = height - 64 - 49 7 webView.frame = CGRectMake(0, 64, width, webViewHeight) 8 9 }
WKWebView代理
1 private func initWebView() { 2 webView.navigationDelegate = self 3 webView.UIDelegate = self 4 }
WKWebView有一個屬性estimatedProgress
,就是當前網頁加載的進度,所以首先監聽這個屬性。
1 private func initProgressView() { 2 3 progressView = UIProgressView.init(frame: CGRectMake(0, 0, UILayoutDefine.KScreenWidth, 4))
// 這里可以改進度條顏色 4 progressView!.tintColor = UIColor.greenColor() 5 webView.addSubview(progressView!)
//監聽
webView.addObserver(self, forKeyPath: keyPathForProgress, options: [NSKeyValueObservingOptions.New, NSKeyValueObservingOptions.Old], context: nil) 7 8 }
實現代理方法
1 /** 計算進度條 */ 2 override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { 3 if ((object?.isEqual(webView) != nil) && (keyPath! == keyPathForProgress) != nil) { 4 let newProgress = change![NSKeyValueChangeNewKey]?.floatValue 5 let oldProgress = change![NSKeyValueChangeOldKey]?.floatValue 6 7 if newProgress < oldProgress { 8 return 9 } 10 11 if newProgress >= 1 { 12 progressView!.hidden = true 13 progressView!.setProgress(0, animated: false) 14 } else { 15 progressView!.hidden = false 16 progressView!.setProgress(newProgress!, animated: true) 17 } 18 } else { 19 super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) 20 } 21 }
1 /** 2 移除消息通知 3 */ 4 deinit { 5 webView .removeObserver(self, forKeyPath: keyPathForProgress) 6 webView.navigationDelegate = nil 7 webView.UIDelegate = nil 8 }
OK 完成
參考:http://nshipster.cn/wkwebkit/