1.導(dǎo)入頭文件
#import <WebKit/WebKit.h>
- 創(chuàng)建webView progressView屬性并且遵循代理
@interface ViewController ()<WKNavigationDelegate>
@property (nonatomic, weak) WKWebView *webView;
@property (nonatomic, weak) UIProgressView *progressView;
@end
3.1 初始化屬性--WKWebView
#pragma mark - 初始化
- (void)setupWebView
{
// 創(chuàng)建WKWebView
WKWebView *webView = [[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
webView.navigationDelegate = self;
// 設(shè)置訪問的URL
NSURL *url = [NSURL URLWithString:@"http://blog.csdn.net/mykingsaber"];
// 根據(jù)URL創(chuàng)建請求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// WKWebView加載請求
[webView loadRequest:request];
// 將WKWebView添加到視圖
[self.view addSubview:webView];
_webView = webView;
[_webView addObserver:self
forKeyPath:NSStringFromSelector(@selector(estimatedProgress))
options:0
context:nil];
}
3.2 初始化屬性--UIProgressView
- (void)setupProgressView
{
UIProgressView *progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
progressView.frame = CGRectMake(0, 20, 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];
_progressView = progressView;
}
- 實現(xiàn)代理方法,我們可以看到代理的調(diào)用順序
#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
NSLog(@"didStartProvisionalNavigation");
//開始加載的時候,讓進(jìn)度條顯示
self.progressView.hidden = NO;
}
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
NSLog(@"didCommitNavigation");
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
NSLog(@"didFinishNavigation");
}
5.重點實現(xiàn)--kvo 監(jiān)聽進(jìn)度
#pragma mark - KVO
-(void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary<NSKeyValueChangeKey,id> *)change
context:(void *)context{
if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))]
&& object == self.webView) {
[self.progressView setAlpha:1.0f];
BOOL animated = self.webView.estimatedProgress > self.progressView.progress;
[self.progressView setProgress:self.webView.estimatedProgress
animated:animated];
if (self.webView.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];
}
}
以上可以直接在控制器中使用, 有興趣的可以直接寫個demo調(diào)試一番 .
開發(fā)點滴, 你我共享.