1. WKWebView的特性:参考文章
在性能、稳定性、功能方面有很大提升(最直观的体现就是加载网页是占用的内存,模拟器加载百度与开源中国网站时,WKWebView占用23M,而UIWebView占用85M);
1.允许JavaScript的Nitro库加载并使用(UIWebView中限制);
2.支持了更多的HTML5特性;
3.高达60fps的滚动刷新率以及内置手势;
4.将UIWebViewDelegate与UIWebView重构成了14类与3个协议(查看苹果官方文档);
2. WKWebView有一个属性estimatedProgress,就是当前网页加载的进度,所以首先监听这个属性。
2.1 创建一个进度条
@property (nonatomic, strong) UIProgressView *progressView;
self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
[self.progressView setTrackTintColor:[UIColor colorWithWhite:1.0f alpha:0.0f]];
[self.progressView setFrame:CGRectMake(0, 0, self.frame.size.width, self.progressView.frame.size.height)];
//设置进度条颜色
[self setTintColor:Color_Red];
[self addSubview:self.progressView];
2.2 KVO 监听
static void *WkWebBrowserContext = &WkWebBrowserContext;
[_wkWebView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:WkWebBrowserContext];
2.3 Estimated Progress KVO (WKWebView)
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.wkWebView) {
[self.progressView setAlpha:1.0f];
BOOL animated = self.wkWebView.estimatedProgress > self.progressView.progress;
[self.progressView setProgress:self.wkWebView.estimatedProgress animated:animated];
// Once complete, fade out UIProgressView
if(self.wkWebView.estimatedProgress >= 1.0f) {
[UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
[self.progressView setAlpha:0.0f];
} completion:^(BOOL finished) {
[self.progressView setProgress:0.0f animated:NO];
}];
}
}
else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
注:可以将wkwebview 与进度条view封装成一个UIView 然后在加载到控制器中