ios首次加载web_ios加载webview显示进度条OC版

APP中WKWebView 和UIWebView都可以加载网页,平时用到的也不多,习惯了UIWebView,近期公司APP做性能优化,监测内存占用,发现加载一个UIWebView界面内存竟然增加了20M,这个不能忍受,并且APP的内存不会以界面的消耗而立即释放,所以使用了WKWebView,监测结果内存增加可忽略不计。孰优孰劣,一目了然。

WKWebView加载网页进度跳显示主要效果如下:

webView.gif

实现webView进度条主要是使用KVO监听WKWebView的“estimatedProgress”属性,通过监听该属性的变化才是进度条的长度。

1、导入#import

2、初始化相关控件创建webview控件,并监听estimatedProgress,加载webView文本方法同UIWebView,不做演示。

@property (nonatomic,strong) WKWebView *WKWebView;

@property (nonatomic,strong) CALayer *progresslayer;

self.WKWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, k_width, k_height-64)];

self.WKWebView.navigationDelegate = self;

[self.view addSubview:self.WKWebView];

self.progresslayer = [[CALayer alloc]init];

self.progresslayer.frame = CGRectMake(0, 0, k_width*0.1, 2);

self.progresslayer.backgroundColor = [UIColor redColor].CGColor;

[self.view.layer addSublayer:self.progresslayer];

[self.WKWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];

3、监听estimatedProgress属性变化,并修改进度条长度,创建进度条的时候之所以给一定的默认长度主要是因为在没有网络的状态下会立即进度float == 1条件,这样给人的感觉就是没有加载网页一样。

// 观察者

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

if ([keyPath isEqualToString:@"estimatedProgress"]) {

self.progresslayer.opacity = 1;

float floatNum = [[change objectForKey:@"new"] floatValue];

self.progresslayer.frame = CGRectMake(0, 0, k_width*floatNum, 2);

if (floatNum == 1) {

__weak __typeof(self)weakSelf = self;

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

weakSelf.progresslayer.opacity = 0;

});

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

weakSelf.progresslayer.frame = CGRectMake(0, 0, 0, 3);

});

}

}else{

[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];

}

}

4、delloc

-(void)dealloc{

[self.WKWebView removeObserver:self forKeyPath:@"estimatedProgress"];

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值