1.m中声明两个属性
@property (nonatomic, strong) WKWebView *wkWebView; @property (nonatomic, strong) UIProgressView *progressView; @property (nonatomic, assign) NSUInteger loadCount;
2.初始化方法自己写
.......
3.添加KVO
<pre><code>通过监听estimatedProgress可以获取它的加载进度 还可以监听它的title ,URL, loading
[wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];</pre></code>
4.计算进度条
<pre><code>- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"loading"]) {
} else if ([keyPath isEqualToString:@"title"]) {
self.title = self.wKWebView.title;
} else if ([keyPath isEqualToString:@"URL"]) {
} else if ([keyPath isEqualToString:@"estimatedProgress"]) {
self.progressView.progress = self.wKWebView.estimatedProgress;
}
if (object == self.wKWebView && [keyPath isEqualToString:@"estimatedProgress"]) {
CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
if (newprogress == 1) {
self.progressView.hidden = YES;
[self.progressView setProgress:0 animated:NO];
}else {
self.progressView.hidden = NO;
[self.progressView setProgress:newprogress animated:YES];
}
}
}
</pre></code>
代理方法中的实现
<pre><code> - (void)setLoadCount:(NSUInteger)loadCount {
_loadCount = loadCount;
if (loadCount == 0) {
self.progressView.hidden = YES;
[self.progressView setProgress:0 animated:NO];
}else {
self.progressView.hidden = NO;
CGFloat oldP = self.progressView.progress;
CGFloat newP = (1.0 - oldP) / (loadCount + 1) + oldP;
if (newP > 0.95) {
newP = 0.95;
}
[self.progressView setProgress:newP animated:YES];
}
}
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
self.loadCount ++;
}
// 内容返回时
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
self.loadCount --;
}
//失败
- (void)webView:(WKWebView *)webView didFailNavigation: (null_unspecified WKNavigation *)navigation withError:(NSError *)error {
self.loadCount --;
NSLog(@"%@",error);
}
//最后别忘记在dealloc 中取消监听
</pre></code>
网友评论