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

  • 相关阅读:
    Java里的堆(heap)栈(stack)和方法区(method)
    SpringMVC 的 Controller 返回各种视图的处理方式
    Nginx Open File Cache
    HandlerInterceptor与MethodInterceptor
    Mysql的with rollup分组统计功能(5.1以上版本)
    idea中@data不生效
    java中? extends T 和? super T解析
    java8排序
    spring boot gateway自定义限流
    spring boot添加logging不能启动且不报错
  • 原文地址:https://www.cnblogs.com/wanli-leon/p/9248446.html
Copyright © 2011-2022 走看看