ios首次加载web_ios加载webview显示进度条OC版
APP中WKWebView 和UIWebView都可以加載網(wǎng)頁(yè),平時(shí)用到的也不多,習(xí)慣了UIWebView,近期公司APP做性能優(yōu)化,監(jiān)測(cè)內(nèi)存占用,發(fā)現(xiàn)加載一個(gè)UIWebView界面內(nèi)存竟然增加了20M,這個(gè)不能忍受,并且APP的內(nèi)存不會(huì)以界面的消耗而立即釋放,所以使用了WKWebView,監(jiān)測(cè)結(jié)果內(nèi)存增加可忽略不計(jì)。孰優(yōu)孰劣,一目了然。
WKWebView加載網(wǎng)頁(yè)進(jìn)度跳顯示主要效果如下:
webView.gif
實(shí)現(xiàn)webView進(jìn)度條主要是使用KVO監(jiān)聽(tīng)WKWebView的“estimatedProgress”屬性,通過(guò)監(jiān)聽(tīng)該屬性的變化才是進(jìn)度條的長(zhǎng)度。
1、導(dǎo)入#import
2、初始化相關(guān)控件創(chuàng)建webview控件,并監(jiān)聽(tīng)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、監(jiān)聽(tīng)estimatedProgress屬性變化,并修改進(jìn)度條長(zhǎng)度,創(chuàng)建進(jìn)度條的時(shí)候之所以給一定的默認(rèn)長(zhǎng)度主要是因?yàn)樵跊](méi)有網(wǎng)絡(luò)的狀態(tài)下會(huì)立即進(jìn)度f(wàn)loat == 1條件,這樣給人的感覺(jué)就是沒(méi)有加載網(wǎng)頁(yè)一樣。
// 觀(guān)察者
-(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"];
}
總結(jié)
以上是生活随笔為你收集整理的ios首次加载web_ios加载webview显示进度条OC版的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 电脑桌面左下角点关机关不了电脑桌面左下角
- 下一篇: 华为荣耀20和x10比较_荣耀x10和荣