- 在webview頂部添加一個進度條UIProgressView。
- 給webVIew添加一個監聽屬性“estimatedProgress”。
- 在監聽事件中,設置ProgressView 的進度等於webview的estimatedProgress。
添加WKWebView,並給WKWebView添加監聽事件
- (void)addWKWebView{
// 創建WKWebView
if (@available(iOS 8.0, *)) {
self.wkWebView = [[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
} else {
// Fallback on earlier versions
}
_wkWebView.backgroundColor = [UIColor whiteColor];
_wkWebView.navigationDelegate = self;
// 設置訪問的URL
NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];
// 根據URL創建請求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// WKWebView加載請求
[_wkWebView loadRequest:request];
// 將WKWebView添加到視圖
[self.view addSubview:_wkWebView];
//給WKWebView添加監聽
[_wkWebView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:nil];
}
給WKWebView添加ProgressView
- (void)addProgressView{
self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
_progressView.frame = CGRectMake(0, 44, SCREEN_WIDTH, 5);
[_progressView setTrackTintColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0]];
_progressView.progressTintColor = [UIColor greenColor];
[self.view addSubview:_progressView];
}
WKNavigationDelegate 代理方法
#pragma mark - WKNavigationDelegate
/**
開始加載
@param webView webView description
@param navigation navigation description
*/
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation API_AVAILABLE(ios(8.0)){
NSLog(@"頁面開始加載時調用");
//開始加載的時候,讓進度條顯示
self.progressView.hidden = NO;
}
-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation API_AVAILABLE(ios(8.0)){
NSLog(@"didCommitNavigation");
}
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation API_AVAILABLE(ios(8.0)){
NSLog(@"didFinishNavigation");
}
監聽方法實現
#pragma mark - KVO
//kvo 監聽進度
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))]
&& object == self.wkWebView) {
[self.progressView setAlpha:1.0f];
BOOL animated = self.wkWebView.estimatedProgress > self.progressView.progress;
[self.progressView setProgress:self.wkWebView.estimatedProgress
animated:animated];
if (self.wkWebView.estimatedProgress >= 1.0f) {
[UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
[self.progressView setAlpha:0.0f];
} completion:^(BOOL finished) {
[self.progressView setProgress:0.0f animated:NO];
}];
}
}else{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
移除監聽事件
-(void)dealloc {
[self.wkWebView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
self.wkWebView.navigationDelegate = nil;
}