WkWebView進度條
阿新 • • 發佈:2019-01-05
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"];
}
文/飛菸灰滅(簡書作者)
原文連結:http://www.jianshu.com/p/24b3e3ddc946
著作權歸作者所有,轉載請聯絡作者獲得授權,並標註“簡書作者”。