iOS-WebView(WKWebView)進度條

來源:互聯網
上載者:User

標籤:網頁   ESS   sla   ali   time   ict   res   ons   工作   

  一直以來,就有想通過技術部落格來記錄總結下自己工作中碰到的問題的想法,這個想法拖了好久今天才開始著手寫自己的第一篇技術部落格,由於剛開始寫,不免會出現不對的地方,希望各位看到的大牛多多指教。好了,不多說了,直接進入正題~

  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

iOS-WebView(WKWebView)進度條

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.