標籤:demo obj 技術分享 初始化 strong 擷取 cal self lan
一、效果展示
WKWebProgressViewDemo.gif二、主要步驟
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]; //設定進度條的高度,下面這句代碼錶示進度條的寬度變為原來的1倍,高度變為原來的1.5倍. self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f); [self.view addSubview:self.progressView];}
3.添加KVO,WKWebView有一個屬性estimatedProgress,就是當前網頁載入的進度,所以監聽這個屬性。
[self.wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
4.在監聽方法中擷取網頁載入的進度,並將進度賦給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變為1.4倍,在開始載入網頁的代理中會恢複為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(@"開始載入網頁"); //開始載入網頁時展示出progressView self.progressView.hidden = NO; //開始載入網頁的時候將progressView的Height恢複為1.5倍 self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f); //防止progressView被網頁擋住 [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中取消監聽
- (void)dealloc { [self.wkWebView removeObserver:self forKeyPath:@"estimatedProgress"];}
三、github 代碼地址
請戳這裡查看demo
iOS WKWebView添加網頁載入進度條(轉)