在进行网页的请求的时候,很多情况下需要显示进度条,来显示加载网页的进度
第一步:设置进度条的基本属性
UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0)];
progressView.tintColor = [UIColor orangeColor];
progressView.trackTintColor = [UIColor whiteColor];
[self.view addSubview:progressView];
self.progressView = progressView;
第二步:监听网页的加载进度
[wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
NSURLRequest *request = [NSURLRequest requestWithURL:_homeUrl];
[wkWebView loadRequest:request];
第三步:实现监听方法:KVO
// 计算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];
}
}
}