我們開發(fā)詳情頁面,有的時(shí)候需要計(jì)算webView或者WKWebView的高度,然后再計(jì)算scrollView的高度,把webView放到scrollView上面。但是計(jì)算webView高度這個(gè)過程很耗費(fèi)時(shí)間,原因是以下代理,網(wǎng)頁徹底加載完才會(huì)計(jì)算出來高度,我們需要的是先算出高度,先出現(xiàn)網(wǎng)頁的文字,至于網(wǎng)頁的圖片,可以慢慢緩存顯示全。這樣不至于白屏?xí)r間過長(zhǎng)。
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
? ? /**計(jì)算高度*/
? ? dispatch_async(dispatch_get_global_queue(0,0), ^{
? ? ? ? [_webView evaluateJavaScript:@"document.documentElement.offsetHeight" completionHandler:^(id_Nullable result, NSError *_Nullable error) {
? ? ? ? ? ? //獲取webView高度
? ? ? ? ? ? CGRect frame = _webView.frame;
? ? ? ? ? ? frame.size.height = [result doubleValue] + 50;
? ? ? ? ? ? _webView.frame = frame;
? ? ? ? ? ? _scrollViewHeight = 220 + _webView.height;
? ? ? ? ? ? _scrollView.contentSize = CGSizeMake(kScreenWidth, _scrollViewHeight);
? ? ? ? }];
? ? });
}
注:上邊的代理被棄用,太耗費(fèi)時(shí)間了。取而代之用下面的方法:(用的WKWebView舉例說明的)
---------------------
第一步:添加觀察者
[_webView.scrollView addObserver:selfforKeyPath:@"contentSize"options:NSKeyValueObservingOptionNewcontext:nil];
第二步:觀察者監(jiān)聽webView的contentSize變化
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
? ? if ([keyPath isEqualToString:@"contentSize"]) {
? ? ? ? dispatch_async(dispatch_get_global_queue(0,0), ^{
? ? ? ? ? ? //document.documentElement.scrollHeight
? ? ? ? ? ? //document.body.offsetHeight
? ? ? ? ? ? [_webView evaluateJavaScript:@"document.documentElement.offsetHeight"completionHandler:^(id_Nullable result, NSError * _Nullable error) {
? ? ? ? ? ? ? ? CGRect frame =_webView.frame;
? ? ? ? ? ? ? ? frame.size.height = [result doubleValue] + 50;
? ? ? ? ? ? ? ? _webView.frame = frame;
? ? ? ? ? ? ? ? _scrollViewHeight =220 + _webView.height;
? ? ? ? ? ? ? ? _scrollView.contentSize =CGSizeMake(kScreenWidth,_scrollViewHeight);
? ? ? ? ? ? }];
? ? ? ? });
? ? }
}
第三步:移除觀察者
- (void)dealloc
{
? ? [_webView.scrollView removeObserver:selfforKeyPath:@"contentSize"];
}
總結(jié):以上這個(gè)方法,不能說特別快速加載,但是在我這里速度至少提升了幾倍。我也在找更好的優(yōu)化方法,比如緩存等等。有知道的更好的方法,歡迎貼出來,大家共享??!
---------------------