WKWebView添加加载进度条


WKWebView添加加载进度条

1,先懒加载一个进度条。

#pragma mark - ***** 进度条 - (UIProgressView *)progressView { if (!_progressView) { UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0)]; progressView.tintColor = [UIColor blueColor]; progressView.trackTintColor = [UIColor magentaColor]; [self.view addSubview:progressView]; self.progressView = progressView; } return _progressView; }

2,初始化WKWebView。

WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds]; wkWebView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; wkWebView.backgroundColor = [UIColor whiteColor]; wkWebView.navigationDelegate = self; /*! 适应屏幕 */ // wkWebView.scalesPageToFit = YES; /*! 解决iOS9.2以上黑边问题 */ wkWebView.opaque = NO; /*! 关闭多点触控 */ wkWebView.multipleTouchEnabled = YES; /*! 加载网页中的电话号码,单击可以拨打 */ // wkWebView.dataDetectorTypes = YES; [self.view insertSubview:wkWebView belowSubview:_progressView]; [wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_urlString]]; [wkWebView loadRequest:request]; self.wkWebView = wkWebView;

3,在KVO中设置相关逻辑

#pragma mark 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (object == self.wkWebView && [keyPath isEqualToString:@"estimatedProgress"])
    {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1)
        {
            self.progressView.hidden = YES;
            [self.progressView setProgress:0 animated:NO];
        }
        else
        {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM