WKWebView 加载进度条

前言

项目开发中我们移动端有很多的纯展示的界面,一般为了方便期间我们都会采用加载 WebView 的方式来做.本篇文章主要介绍在加载 WebView 时候顶部显示一个进度条

//记得导入以下库
#import 

@interface ZNHelpCenterVC ()
/** webView */
@property (nonatomic , strong) WKWebView *wkWebView;
@property (weak, nonatomic) CALayer *progresslayer;//进度条

@end

@implementation ZNHelpCenterVC

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.navigationItem.title = @"我的";
    _wkWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, NavigationBarHeight, kScreenWidth, kScreenHeight-NavigationBarHeight)];
    [_wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    _wkWebView.backgroundColor = ZNWhiteColor;
    
    NSURL *contentUrl = [NSURL URLWithString:@"http://www.jianshu.com/u/f9deb1426e04"];
    NSURLRequest *request = [NSURLRequest requestWithURL:contentUrl];
    [self.view addSubview:_wkWebView];
    //进度条
    UIView *progress = [[UIView alloc]initWithFrame:CGRectMake(0, NavigationBarHeight, kScreenWidth, 2)];
    progress.backgroundColor = [UIColor clearColor];
    [self.view addSubview:progress];
    CALayer *layer = [CALayer layer];
    layer.frame = CGRectMake(0, 0, 0, 2);
    layer.backgroundColor = ZNCommonColor.CGColor;
    [progress.layer addSublayer:layer];
    self.progresslayer = layer;
    //加载网址
    [_wkWebView loadRequest:request];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progresslayer.opacity = 1;
        self.progresslayer.frame = CGRectMake(0, 0, kScreenWidth * [change[NSKeyValueChangeNewKey] floatValue], 2);
        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, 2);
            });
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

//移除观察者
- (void)dealloc{
    [_wkWebView removeObserver:self forKeyPath:@"estimatedProgress"];
}

你可能感兴趣的:(WKWebView 加载进度条)