標籤:網頁 ESS sla ali time ict res ons 工作
一直以來,就有想通過技術部落格來記錄總結下自己工作中碰到的問題的想法,這個想法拖了好久今天才開始著手寫自己的第一篇技術部落格,由於剛開始寫,不免會出現不對的地方,希望各位看到的大牛多多指教。好了,不多說了,直接進入正題~
WKWebView有一個屬性estimatedProgress,該屬性就是當前網頁載入的進度,可以通過KVO來監聽這個屬性。
WKWebView * webView = [[WKWebView alloc] initWithFrame:self.view.bounds];[self.view addSubview:webView];self.webView = webView;// 添加屬性監聽[webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
添加好屬性的監聽後,接下來就是去實現進度條,這裡用到了CALayer隱式動畫
// 進度條UIView * progress = [[UIView alloc] initWithFrame:CGRectMake(0, 64, CGRectGetWidth(self.view.frame), 3)];progress.backgroundColor = [UIColor clearColor];
[self.view addSubview:progress]; // 隱式動畫CALayer * layer = [CALayer layer];layer.frame = CGRectMake(0, 0, 0, 3);layer.backgroundColor = [UIColor blueColor].CGColor;[progress.layer addSublayer:layer];self.progressLayer = layer;
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]
做好這些基本的工作之後,就是最重要的監聽屬性的方法了
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{ if ([keyPath isEqualToString:@"estimatedProgress"]) { NSLog(@"change == %@",change); self.progressLayer.opacity = 1; self.progressLayer.frame = CGRectMake(0, 0, self.view.bounds.size.width * [change[NSKeyValueChangeNewKey] floatValue], 3); if ([change[NSKeyValueChangeNewKey] floatValue] == 1) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ self.progressLayer.opacity = 0; }); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ self.progressLayer.frame = CGRectMake(0, 0, 0, 3); }); } }else { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; }}
主要的代碼就是這些了,??最後不要忘記取消監聽
- (void)dealloc { [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];}
以上就是給WKWebView添加進度條的方式。最後附上實現的Demo:https://github.com/wanliju/WLWKWebViewWithProgressLine
iOS-WebView(WKWebView)進度條