下面介绍在webview中添加加载进度条的代码。具体的思路看代码一目了然😆
[self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
DLOG(@"%@", webView.URL);
[self.progressView setProgress:.15 animated:YES];
}
// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (object == self.newedWebView && [keyPath isEqualToString:@"estimatedProgress"]) {
CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
if (self.progressView.hidden) self.progressView.hidden = NO;
[self.progressView setProgress:newprogress animated:YES];
if (newprogress == 1) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.progressView.hidden = YES;
}); }
}else{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- (UIProgressView *)progressView {
if(!_progressView) {
_progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, self.navBar.maxY, MSWIDTH, 0)];
_progressView.progressViewStyle = UIProgressViewStyleBar;
_progressView.tintColor = RGB(218, 187, 63);
_progressView.trackTintColor = [UIColor clearColor];
[self.view addSubview:_progressView]; }
return _progressView;
}
- (void)dealloc {
[self.newedWebView removeObserver:self forKeyPath:@"estimatedProgress"];
}