zoukankan      html  css  js  c++  java
  • iOS-WebView(WKWebView)进度条

      一直以来,就有想通过技术博客来记录总结下自己工作中碰到的问题的想法,这个想法拖了好久今天才开始着手写自己的第一篇技术博客,由于刚开始写,不免会出现不对的地方,希望各位看到的大牛多多指教。好了,不多说了,直接进入正题~

      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

  • 相关阅读:
    spring和设计模式
    Chrome插件下载网站图片
    MySql Illegal mix of collations 问题
    通过优化配置,提高MySql性能
    Windows下将Spring jar包部署为一个服务
    Apereo CAS增加登录方式。
    信息学竞赛C++基础教程
    关于codedecision和我本人
    信息学竞赛C++教程5.循环结构程序设计
    信息学竞赛C++教程3.分支结构程序设计
  • 原文地址:https://www.cnblogs.com/wanli-leon/p/9248446.html
Copyright © 2011-2022 走看看