美文网首页iOS技术帖
iOS WKWebView添加类似微信的进度条

iOS WKWebView添加类似微信的进度条

作者: 刘宇航iOS | 来源:发表于2016-05-11 10:35 被阅读7490次

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>

相关文章

网友评论

  • 做你的小星星:可以配合NJKWebViewProgressView使用,效果应该会更好一点!
  • 瑞廷:大神,有demo没?先谢了
  • cssshuang:你好,请教一下,通过KVO就可以改变进度条的状态,为什么还要用代理方法呢?

本文标题:iOS WKWebView添加类似微信的进度条

本文链接:https://www.haomeiwen.com/subject/zazyrttx.html