iOS中WKWebView仿微信加載進度條

這篇文章主要爲大家詳細介紹了iOS中WKWebView仿微信加載進度條,具有一定的參考價值,感興趣的小夥伴們可以參考一下

本文實例爲大家分享了WKWebView仿微信加載進度條的具體代碼,供大家參考,具體內容如下

WKWebView添加了estimatedProgress屬性(double類型),我們可以利用該屬性來設置UIProgressView

github代碼倉庫上存放的Demo

爲頁面添加UIProgressView屬性

@property (nonatomic, strong) WKWebView *mywebView;
@property (nonatomic, strong) UIProgressView *progressView;//設置加載進度條

懶加載UIProgressView

-(UIProgressView *)progressView{
 if (!_progressView) {
  _progressView     = [[UIProgressView alloc]
           initWithProgressViewStyle:UIProgressViewStyleDefault];
  _progressView.frame    = CGRectMake(0, 64, screen_width, 5);

  [_progressView setTrackTintColor:[UIColor colorWithRed:240.0/255
               green:240.0/255
               blue:240.0/255
               alpha:1.0]];
  _progressView.progressTintColor = [UIColor greenColor];


 }
 return _progressView;
}

在初始化WKWebView時(我是在懶加載時) kvo 添加監控

 [_mywebView addObserver:self
      forKeyPath:NSStringFromSelector(@selector(estimatedProgress))
      options:0
      context:nil];

頁面開始加載時,隱藏進度條

//開始加載
-(void)webView:(WKWebView *)webView
 didStartProvisionalNavigation:(WKNavigation *)navigation{
 //開始加載的時候,讓進度條顯示
 self.progressView.hidden = NO;
}

kvo 監聽進度

//kvo 監聽進度
-(void)observeValueForKeyPath:(NSString *)keyPath
      ofObject:(id)object
      change:(NSDictionary<NSKeyValueChangeKey,id> *)change
      context:(void *)context{

 if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))]
  && object == self.mywebView) {
  [self.progressView setAlpha:1.0f];
  BOOL animated = self.mywebView.estimatedProgress > self.progressView.progress;
  [self.progressView setProgress:self.mywebView.estimatedProgress
        animated:animated];

  if (self.mywebView.estimatedProgress >= 1.0f) {
   [UIView animateWithDuration:0.3f
         delay:0.3f
        options:UIViewAnimationOptionCurveEaseOut
        animations:^{
         [self.progressView setAlpha:0.0f];
        }
        completion:^(BOOL finished) {
         [self.progressView setProgress:0.0f animated:NO];
        }];
  }
 }else{
  [super observeValueForKeyPath:keyPath
        ofObject:object
        change:change
        context:context];
 }
}

在dealloc方法裏移除監聽

-(void)dealloc{
 [self.mywebView removeObserver:self
      forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章