白羽
2018-07-16
来源 :网络
阅读 1347
评论 0
摘要:本文将带你了解iOS开发之iOS-WebView(WKWebView)进度条,希望本文对大家学IOS有所帮助。
一直以来,就有想通过技术博客来记录总结下自己工作中碰到的问题的想法,这个想法拖了好久今天才开始着手写自己的第一篇技术博客,由于刚开始写,不免会出现不对的地方,希望各位看到的大牛多多指教。好了,不多说了,直接进入正题~
WKWebView有一个属性estimatedProgress,该属性就是当前网页加载的进度,可以通过KVO来监听这个属性。
WKWebView * webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:webView];
self.webView = webView;
// 添加属性监听
[webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
添加好属性的监听后,接下来就是去实现进度条,这里用到了CALayer隐式动画
// 进度条
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 = [UIColor blueColor].CGColor;
[progress.layer addSublayer:layer];
self.progressLayer = layer;
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]
做好这些基本的工作之后,就是最重要的监听属性的方法了
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
if ([keyPath isEqualToString:@"estimatedProgress"]) {
NSLog(@"change == %@",change);
self.progressLayer.opacity = 1;
self.progressLayer.frame = CGRectMake(0, 0, self.view.bounds.size.width * [change[NSKeyValueChangeNewKey] floatValue], 3);
if ([change[NSKeyValueChangeNewKey] floatValue] == 1) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.progressLayer.opacity = 0;
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.8 * 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];
}
}
主要的代码就是这些了,⚠️最后不要忘记取消监听
- (void)dealloc {
[self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}
以上就是给WKWebView添加进度条的方式。最后附上实现的Demo:https://github.com/wanliju/WLWKWebViewWithProgressLine
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之IOS频道!
喜欢 | 0
不喜欢 | 0
您输入的评论内容中包含违禁敏感词
我知道了

请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号