WKWebview 添加加载进度条

1. WKWebView的特性:参考文章

在性能、稳定性、功能方面有很大提升(最直观的体现就是加载网页是占用的内存,模拟器加载百度与开源中国网站时,WKWebView占用23M,而UIWebView占用85M);

1.允许JavaScript的Nitro库加载并使用(UIWebView中限制);
2.支持了更多的HTML5特性;
3.高达60fps的滚动刷新率以及内置手势;
4.将UIWebViewDelegate与UIWebView重构成了14类与3个协议(查看苹果官方文档);

2. WKWebView有一个属性estimatedProgress,就是当前网页加载的进度,所以首先监听这个属性。
2.1 创建一个进度条

@property (nonatomic, strong) UIProgressView *progressView;

self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
[self.progressView setTrackTintColor:[UIColor colorWithWhite:1.0f alpha:0.0f]];
[self.progressView setFrame:CGRectMake(0, 0, self.frame.size.width, self.progressView.frame.size.height)];
//设置进度条颜色
[self setTintColor:Color_Red];
[self addSubview:self.progressView];
2.2 KVO 监听

static void *WkWebBrowserContext = &WkWebBrowserContext;

[_wkWebView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:WkWebBrowserContext];
2.3 Estimated Progress KVO (WKWebView)
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.wkWebView) {
    [self.progressView setAlpha:1.0f];
    BOOL animated = self.wkWebView.estimatedProgress > self.progressView.progress;
    [self.progressView setProgress:self.wkWebView.estimatedProgress animated:animated];
    
    // Once complete, fade out UIProgressView
    if(self.wkWebView.estimatedProgress >= 1.0f) {
        [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
            [self.progressView setAlpha:0.0f];
        } completion:^(BOOL finished) {
            [self.progressView setProgress:0.0f animated:NO];
        }];
    }
}
else {
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}

注:可以将wkwebview 与进度条view封装成一个UIView 然后在加载到控制器中
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1、添加UIProgressView属性 2、初始化progressView (void)viewDidLoad ...
    张晓刚_云字节阅读 5,316评论 0 0
  • iOS8以后,苹果推出了新框架Wekkit,提供了替换UIWebView的组件WKWebView。各种UIWebV...
    陌上北辰阅读 3,775评论 0 0
  • 通过学习,你将会学习以下几个方面的内容: **什么是WKWebView以及它和UIWebView的区别是什么 **...
    SOI阅读 14,034评论 18 42
  • WKWebView 新特性 加载 web 页面 加载本地资源 - loadHTMLString:baseURL:同...
    独木舟的木阅读 22,320评论 2 43
  • 有点担心给你的礼物会做不好,上次给你的兔子就被我做的面目全非,所以这次很担心这两个会不会做好
    雪空云依阅读 1,540评论 3 0

友情链接更多精彩内容