您好,欢迎来到华佗小知识。
搜索
您的当前位置:首页webView进度条加载

webView进度条加载

来源:华佗小知识
#import "informationDetailViewController.h"
#import <WebKit/WebKit.h>
@interface informationDetailViewController ()<WKNavigationDelegate>
@property (nonatomic, strong) WKWebView * webView;
@property(nonatomic)CALayer *progresslayer;
@end
@implementation informationDetailViewController

- (void)viewDidLoad {
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    self.webView.scrollView.bounces = NO;
    self.webView.navigationDelegate = self;
    self.webView.backgroundColor = Default_BackgroudColor;
    //给webView添加KVO监听
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.view addSubview:self.webView];
    //创建进度条
    UIView * progress = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 2)];
    progress.backgroundColor = [UIColor clearColor];
    [self.view addSubview:progress];
    //给进度条添加layer层
    CALayer *layer = [CALayer layer];
    layer.frame = CGRectMake(0, 0, 0, 1);
    layer.backgroundColor = color_lan_se_an_niu.CGColor;
    [progress.layer addSublayer:layer];
    self.progresslayer = layer;
}
- (void)viewWillAppear:(BOOL)animated {
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL 
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progresslayer.opacity = 1;
        //不要让进度条倒着走...有时候goback会出现这种情况
        if ([change[@"new"] floatValue] < [change[@"old"] floatValue]) {
            return;
        }
        NSLog(@"progress%f",[change[@"new"] floatValue] );
        self.progresslayer.frame = CGRectMake(0, 0, self.view.bounds.size.width * [change[@"new"] floatValue], 2);
        if ([change[@"new"] floatValue] == 1) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progresslayer.opacity = 0;
            });
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progresslayer.frame = CGRectMake(0, 0, 0, 2);
            });
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    [self removeObserver:self forKeyPath:@"estimatedProgress"];
}
@end

示例图片如下

WechatIMG29.jpeg

Copyright © 2019- huatuo0.cn 版权所有 湘ICP备2023017654号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务