WKWebView添加进度条
2016-07-04 本文已影响4527人
IT小妞儿
- 代码如下
@interface ViewController () <WKNavigationDelegate>
/**
* webView
*/
@property (nonatomic, strong) WKWebView *webView;
@property (strong, nonatomic) UIProgressView *progressView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];
}
#pragma mark - WKWebView代理
// 如果不添加这个,那么wkwebview跳转不了AppStore
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
if ([webView.URL.absoluteString hasPrefix:@"https://itunes.apple.com"]) {
[[UIApplication sharedApplication] openURL:navigationAction.request.URL];
decisionHandler(WKNavigationActionPolicyCancel);
}else {
decisionHandler(WKNavigationActionPolicyAllow);
}
}
// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
if (newprogress == 1) {
self.progressView.hidden = YES;
[self.progressView setProgress:0 animated:NO];
}else {
self.progressView.hidden = NO;
[self.progressView setProgress:newprogress animated:YES];
}
}
}
// 记得取消监听
- (void)dealloc {
[self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}
#pragma mark - lazy
- (WKWebView *)webView
{
if(!_webView)
{
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, QQMScreenWidth, QQMScreenHeight)];
_webView.navigationDelegate = self;
[_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
[self.view insertSubview:_webView belowSubview:self.progressView];
}
return _webView;
}
- (UIProgressView *)progressView
{
if(!_progressView)
{
_progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, QQMNavH + QQMStatusH, QQMScreenWidth, 0)];
self.progressView.tintColor = [UIColor orangeColor];
self.progressView.trackTintColor = [UIColor whiteColor];
[self.view addSubview:self.progressView];
}
return _progressView;
}
@end