一川抡、效果展示
二敌完、主要步驟
1.添加UIProgressView屬性
@property (nonatomic, strong) WKWebView *wkWebView;
@property (nonatomic, strong) UIProgressView *progressView;
2.初始化progressView
- (void)viewDidLoad {
[super viewDidLoad];
//進度條初始化
self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 20, [[UIScreen mainScreen] bounds].size.width, 2)];
self.progressView.backgroundColor = [UIColor blueColor];
//設置進度條的高度,下面這句代碼表示進度條的寬度變?yōu)樵瓉淼?倍揍诽,高度變?yōu)樵瓉淼?.5倍.
self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
[self.view addSubview:self.progressView];
}
3.添加KVO愉适,WKWebView有一個屬性estimatedProgress犯助,就是當前網(wǎng)頁加載的進度,所以監(jiān)聽這個屬性维咸。
[self.wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
4.在監(jiān)聽方法中獲取網(wǎng)頁加載的進度剂买,并將進度賦給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) {
/*
*添加一個簡單的動畫,將progressView的Height變?yōu)?.4倍癌蓖,在開始加載網(wǎng)頁的代理中會恢復為1.5倍
*動畫時長0.25s瞬哼,延時0.3s后開始動畫
*動畫結束后將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的代理中展示進度條,加載完成后隱藏進度條
//開始加載
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
NSLog(@"開始加載網(wǎng)頁");
//開始加載網(wǎng)頁時展示出progressView
self.progressView.hidden = NO;
//開始加載網(wǎng)頁的時候將progressView的Height恢復為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"];
}
三租副、github 代碼地址
請戳這里查看demo坐慰,如果覺得還不錯請隨手給個star。