本篇内容比较简单,希望给iOS 新手学习,大神请勿吐槽!谢谢。
内容介绍:
1.在webview顶部添加一个进度条UIProgressView。
2.给webVIew添加一个监听属性“estimatedProgress”。
3.在监听事件中,设置ProgressView 的进度等于webview的estimatedProgress。
废话不多说,直接上代码!
- (void)viewDidLoad {
[super viewDidLoad];
self.webView = [[WKWebView alloc]initWithFrame:self.view.bounds];
self.webView.UIDelegate = self;
self.webView.navigationDelegate = self;
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
[self.view addSubview:self.webView];
self.progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 64, CGRectGetWidth(self.view.frame), 2)];
self.progressView.progressTintColor = [UIColor greenColor];
[self.view addSubview:self.progressView];
// 给webview添加监听
[self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
// Do any additional setup after loading the view, typically from a nib.
}
// 监听事件处理
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
if ([keyPath isEqual:@"estimatedProgress"] && object == self.webView) {
[self.progressView setAlpha:1.0f];
[self.progressView setProgress:self.webView.estimatedProgress animated:YES];
if (self.webView.estimatedProgress >= 1.0f) {
[UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
[self.progressView setAlpha:0.0f];
} completion:^(BOOL finished) {
[self.progressView setProgress:0.0f animated:YES];
}];
}
}else{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- (void)dealloc{
[self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
[self.webView setNavigationDelegate:nil];
[self.webView setUIDelegate:nil];
}
到此结束。所有代码都在此,github地址 https://github.com/wenjing0628/WKWebViewProgress