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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM