给WKWebView添加进度条(swift)

在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/

posted on 2017-01-11 20:25  Walking_Jin  阅读(2137)  评论(0编辑  收藏  举报

导航