iOS 给webView加进度条(WKWebView)

1.导入头文件

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #import <WebKit/WebKit.h>   


2.创建WKWebView和ProcessView, 并且添加观察者

@property (strong, nonatomic) WKWebView *webView;
@property (strong, nonatomic) UIProgressView *progressView;


[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (void)viewDidLoad {  
  2.     [super viewDidLoad];  
  3.     _webView = [[WKWebView alloc] initWithFrame:self.view.bounds];  
  4.     _webView.UIDelegate = self;  
  5.     _webView.navigationDelegate = self;  
  6.     [self.view addSubview:_webView];  
  7.       
  8.     _progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(065, CGRectGetWidth(self.view.frame),2)];  
  9.     [self.view addSubview:_progressView];  
  10.       
  11.     [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];  
  12.     [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];  
  13.   
  14. }  


 

3. 实现代理方法

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(voidvoid *)context{  
  2.     NSLog(@" %s,change = %@",__FUNCTION__,change);  
  3.     if ([keyPath isEqual@"estimatedProgress"] && object == _webView) {  
  4.         [self.progressView setAlpha:1.0f];  
  5.         [self.progressView setProgress:_webView.estimatedProgress animated:YES];  
  6.             if(_webView.estimatedProgress >= 1.0f)  
  7.             {  
  8.                 [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{  
  9.                     [self.progressView setAlpha:0.0f];  
  10.                 } completion:^(BOOL finished) {  
  11.                     [self.progressView setProgress:0.0f animated:NO];  
  12.                 }];  
  13.             }  
  14.     }  
  15.     else {  
  16.         [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];  
  17.     }  
  18. }  


4.移除观察者

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (void)dealloc {  
  2.     [_webView removeObserver:self forKeyPath:@"estimatedProgress"];  
  3.       
  4.     // if you have set either WKWebView delegate also set these to nil here  
  5.     [_webView setNavigationDelegate:nil];  
  6.     [_webView setUIDelegate:nil];  
  7. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值