類似Safari的加載進度條只洒,除了比HUD更加簡潔七扰,也有更好的用戶體驗锉桑。HUD會讓用戶覺得等待的時間很長链韭,因為用戶注意力集中在一個沒有程度變化的東西上面偏竟。而進度條是有程度變化的,所以會讓用戶產生加載速度比HUD快的錯覺敞峭。(本人在公司內調查踊谋,的確如此)。所以現在就行動吧旋讹!
你可能已經注意到了殖蚕,是WebView進度條而不是UIWebView,沒錯這個實現真對的不是UIWebView而是WKWebView沉迹,什么你不知道WKWebView睦疫?趕緊谷歌或者必應一下吧,這個控件要比UIWebView性能強大并且功能豐富鞭呕,關于WKWebView的使用不屬于本篇介紹的范圍蛤育,感興趣的可以自行搜索,后續(xù)我也會寫相關的文章的葫松。
好瓦糕,廢話不多說,進入正題腋么。WKWebView有一個屬性estimatedProgress
刻坊,就是當前網頁加載的進度,所以首先監(jiān)聽這個屬性党晋。
WKWebView *webView = [[WKWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
[webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
self.webView = webView;
接下來谭胚,就是弄一個進度條啦徐块,在viewDidLoad方法里面寫:
UIView *progress = [[UIView alloc]initWithFrame:CGRectMake(0, 64, CGRectGetWidth(self.view.frame), 3)];
progress.backgroundColor = [UIColor clearColor];
[self.view addSubview:progress];
CALayer *layer = [CALayer layer];
layer.frame = CGRectMake(0, 0, 0, 3);
layer.backgroundColor = COLOR_BAR_TIN.CGColor;
[progress.layer addSublayer:layer];
self.progresslayer = layer;
為什么要用CALayer?隱式動畫啊灾而。然后就是監(jiān)聽方法啦
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
if ([keyPath isEqualToString:@"estimatedProgress"]) {
self.progresslayer.opacity = 1;
//不要讓進度條倒著走...有時候goback會出現這種情況
if ([change[@"new"] floatValue] < [change[@"old"] floatValue]) {
return;
}
self.progresslayer.frame = CGRectMake(0, 0, self.view.bounds.size.width * [change[@"new"] floatValue], 3);
if ([change[@"new"] floatValue] == 1) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.progresslayer.opacity = 0;
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.progresslayer.frame = CGRectMake(0, 0, 0, 3);
});
}
}else{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
拷貝到自己的項目里面就OK啦胡控,是不是很爽呢?最后別忘了取消監(jiān)聽...
- (void)dealloc{
[self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}
拿過去給產品show旁趟,告訴他你各種深度優(yōu)化昼激,讓網頁加載提速了,他肯定會說锡搜,「牛逼橙困!」。
應大家要求耕餐,搞了個demo:
https://github.com/timehzy/WebViewWithProgressLine