WKWebView添加加载进度条
1,先懒加载一个进度条。
#pragma mark - ***** 进度条 - (UIProgressView *)progressView { if (!_progressView) { UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0)]; progressView.tintColor = [UIColor blueColor]; progressView.trackTintColor = [UIColor magentaColor]; [self.view addSubview:progressView]; self.progressView = progressView; } return _progressView; }
2,初始化WKWebView。
WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds]; wkWebView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; wkWebView.backgroundColor = [UIColor whiteColor]; wkWebView.navigationDelegate = self; /*! 适应屏幕 */ // wkWebView.scalesPageToFit = YES; /*! 解决iOS9.2以上黑边问题 */ wkWebView.opaque = NO; /*! 关闭多点触控 */ wkWebView.multipleTouchEnabled = YES; /*! 加载网页中的电话号码,单击可以拨打 */ // wkWebView.dataDetectorTypes = YES; [self.view insertSubview:wkWebView belowSubview:_progressView]; [wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_urlString]]; [wkWebView loadRequest:request]; self.wkWebView = wkWebView;
3,在KVO中设置相关逻辑
#pragma mark 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
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];
}
}
}