WkWebView进度条

来源:互联网 发布:android 数据缓存 编辑:程序博客网 时间:2024/06/05 14:20

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
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
0 0