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

  • 相关阅读:
    洛谷 P3389 【模板】高斯消元法
    洛谷 P2090 数字对
    树链剖分
    bzoj3784 树上的路径
    K Seq HihoCoder
    一些奇怪的注意事项
    洛谷 P3437 [POI2006]TET-Tetris 3D
    洛谷 P2048 [NOI2010]超级钢琴 || Fantasy
    JVM字节码指令
    java中什么是Bridge Method(桥接方法)
  • 原文地址:https://www.cnblogs.com/wanli-leon/p/9248446.html
Copyright © 2011-2022 走看看