最近在寫一個電商APP項(xiàng)目詳情頁,采用在UITableViewCell上鑲嵌WKWebView加載純圖片網(wǎng)頁,網(wǎng)頁圖片會因?yàn)榫W(wǎng)絡(luò)延遲加載緩慢,那么問題來了,如何準(zhǔn)確的獲取網(wǎng)頁的總高度呢?
我的解決方法思路是:
當(dāng)商品詳情網(wǎng)頁加載完成后,使用JavaScript獲取html網(wǎng)頁所有的圖片(將js代碼注入到WKWebView中),遍歷所有圖片獲取圖片的寬和高,由于蘋果設(shè)備屏幕尺寸不同,要動態(tài)計(jì)算出單張圖片在不同屏幕尺寸的實(shí)際顯示高度,將計(jì)算的所有圖片實(shí)際顯示高度加起來就是商品詳情頁的準(zhǔn)確高度。
具體代碼實(shí)現(xiàn):
//加載完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
NSLog(@"加載完成");
NSString *js1 = @"function getImagesHeight(screenWidth){var imagesHeight = 0;for(i=0;i <document.images.length;i++){var image = document.images[i];var imgW = image.width;var imgH = image.height;var realImgH = screenWidth*imgH/imgW;imagesHeight += realImgH;} window.webkit.messageHandlers.getWebHeight.postMessage(imagesHeight)}";
NSString *js2 = [NSString stringWithFormat:@"getImagesHeight(%f)",[UIScreen mainScreen].bounds.size.width];
[self.webView evaluateJavaScript:js1 completionHandler:^(id item, NSError * _Nullable error) {
// Block中處理是否執(zhí)行JS錯誤的代碼
}];
[self.webView evaluateJavaScript:js2 completionHandler:^(id item, NSError * _Nullable error) {
// Block中處理是否執(zhí)行JS錯誤的代碼
}];
}
#pragma mark ----------------- WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSLog(@"%@",message.body);
NSLog(@"%@",message.name);
if ([message.name isEqualToString:@"getWebHeight"]) {
NSString *body = [NSString stringWithFormat:@"%@",message.body];
CGFloat webH = body.floatValue;
self.webCellHeight = webH;
self.webView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, self.webCellHeight);
[self.tableView reloadData];
}
}
- (WKWebView *)webView{
if (_webView == nil) {
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) configuration:config];
_webView.scrollView.scrollEnabled = NO;
_webView.navigationDelegate = self;
WKUserContentController *userCC = config.userContentController;
//意思是網(wǎng)頁中需要傳遞的參數(shù)是通過這個JS中的showMessage方法來傳遞的
[userCC addScriptMessageHandler:self name:@"getWebHeight"];
}
return _webView;