WKWebView有一个属性estimatedProgress
,就是当前网页加载的进度,所以首先监听这个属性。
WKWebView *webView = [[WKWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
[webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
接下来,就是弄一个进度条啦,在viewDidLoad方法里面写:
UIView *progress = [[UIView alloc]initWithFrame:CGRectMake(0, 64, CGRectGetWidth(self.view.frame), 3)];
progress.backgroundColor = [UIColor clearColor];
[self.view addSubview:progress];
CALayer *layer = [CALayer layer];
layer.frame = CGRectMake(0, 0, 0, 3);
layer.backgroundColor = COLOR_BAR_TIN.CGColor;
[progress.layer addSublayer:layer];
self.progresslayer = layer;
为什么要用CALayer?隐式动画啊。然后就是监听方法啦
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{ if ([keyPath isEqualToString:@"estimatedProgress"]) { self.progresslayer.opacity = 1;
//不要让进度条倒着走...有时候goback会出现这种情况
if ([change[@"new"] floatValue] < [change[@"old"] floatValue]) { return;
}
self.progresslayer.frame = CGRectMake(0, 0, self.view.bounds.size.width * [change[@"new"] floatValue], 3);
if ([change[@"new"] floatValue] == 1) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ self.progresslayer.opacity = 0;
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.progresslayer.frame = CGRectMake(0, 0, 0, 3);
});
}
}else{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
拷贝到自己的项目里面就OK啦,是不是很爽呢?最后别忘了取消监听...
- (void)dealloc{
[(WKWebView *)self.view removeObserver:self forKeyPath:@"estimatedProgress"];
}