iOS中WKWebView仿微信加载进度条

时间:2021-10-17 08:52:11

本文实例为大家分享了wkwebview仿微信加载进度条的具体代码,供大家参考,具体内容如下

wkwebview添加了estimatedprogress属性(double类型),我们可以利用该属性来设置uiprogressview

github代码仓库上存放的demo

为页面添加uiprogressview属性

?
1
2
@property (nonatomic, strong) wkwebview *mywebview;
@property (nonatomic, strong) uiprogressview *progressview;//设置加载进度条

懒加载uiprogressview

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
-(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 添加监控

?
1
2
3
4
[_mywebview addobserver:self
     forkeypath:nsstringfromselector(@selector(estimatedprogress))
     options:0
     context:nil];

页面开始加载时,隐藏进度条

?
1
2
3
4
5
6
//开始加载
-(void)webview:(wkwebview *)webview
 didstartprovisionalnavigation:(wknavigation *)navigation{
 //开始加载的时候,让进度条显示
 self.progressview.hidden = no;
}

kvo 监听进度

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//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方法里移除监听

?
1
2
3
4
-(void)dealloc{
 [self.mywebview removeobserver:self
      forkeypath:nsstringfromselector(@selector(estimatedprogress))];
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/MyKingSaber/article/details/54134216