一、效果展示

2409226-fd0b88b35434be72.gif
二、主要步驟
1.添加UIProgressView屬性
@property (nonatomic, strong) WKWebView *wkWebView;
@property (nonatomic, strong) UIProgressView *progressView;
2.初始化progressView
- (void)viewDidLoad {
[super viewDidLoad];
//進(jìn)度條初始化
self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 20, [[UIScreen mainScreen] bounds].size.width, 2)];
self.progressView.backgroundColor = [UIColor blueColor];
//設(shè)置進(jìn)度條的高度,下面這句代碼表示進(jìn)度條的寬度變?yōu)樵瓉淼?倍,高度變?yōu)樵瓉淼?.5倍.
self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
[self.view addSubview:self.progressView];
}
注意: UIProgressView有固定默認(rèn)高度
self.progressView.transform = CGAffineTransformMakeScale(1.0f,2.0f);//高度變?yōu)槟J(rèn)的兩倍
3.添加KVO,WKWebView有一個(gè)屬性estimatedProgress,就是當(dāng)前網(wǎng)頁加載的進(jìn)度,所以監(jiān)聽這個(gè)屬性。
[self.wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
4.在監(jiān)聽方法中獲取網(wǎng)頁加載的進(jìn)度,并將進(jìn)度賦給progressView.progress
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"estimatedProgress"]) {
self.progressView.progress = self.wkWebView.estimatedProgress;
if (self.progressView.progress == 1) {
/*
*添加一個(gè)簡(jiǎn)單的動(dòng)畫,將progressView的Height變?yōu)?.4倍,在開始加載網(wǎng)頁的代理中會(huì)恢復(fù)為1.5倍
*動(dòng)畫時(shí)長(zhǎng)0.25s,延時(shí)0.3s后開始動(dòng)畫
*動(dòng)畫結(jié)束后將progressView隱藏
*/
__weak typeof (self)weakSelf = self;
[UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
} completion:^(BOOL finished) {
weakSelf.progressView.hidden = YES;
}];
}
}else{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
5.在WKWebViewd的代理中展示進(jìn)度條,加載完成后隱藏進(jìn)度條
//開始加載
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
NSLog(@"開始加載網(wǎng)頁");
//開始加載網(wǎng)頁時(shí)展示出progressView
self.progressView.hidden = NO;
//開始加載網(wǎng)頁的時(shí)候?qū)rogressView的Height恢復(fù)為1.5倍
self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
//防止progressView被網(wǎng)頁擋住
[self.view bringSubviewToFront:self.progressView];
}
//加載完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
NSLog(@"加載完成");
//加載完成后隱藏progressView
//self.progressView.hidden = YES;
}
//加載失敗
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
NSLog(@"加載失敗");
//加載失敗同樣需要隱藏progressView
//self.progressView.hidden = YES;
}
6.在dealloc中取消監(jiān)聽
- (void)dealloc {
[self.wkWebView removeObserver:self forKeyPath:@"estimatedProgress"];
}