最近在写一个电商APP项目详情页,采用在UITableViewCell上镶嵌WKWebView加载纯图片网页,网页图片会因为网络延迟加载缓慢,那么问题来了,如何准确的获取网页的总高度呢?
我的解决方法思路是:
当商品详情网页加载完成后,使用JavaScript获取html网页所有的图片(将js代码注入到WKWebView中),遍历所有图片获取图片的宽和高,由于苹果设备屏幕尺寸不同,要动态计算出单张图片在不同屏幕尺寸的实际显示高度,将计算的所有图片实际显示高度加起来就是商品详情页的准确高度。
具体代码实现:
//加载完成
- (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中处理是否执行JS错误的代码
}];
[self.webView evaluateJavaScript:js2 completionHandler:^(id item, NSError * _Nullable error) {
// Block中处理是否执行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;
//意思是网页中需要传递的参数是通过这个JS中的showMessage方法来传递的
[userCC addScriptMessageHandler:self name:@"getWebHeight"];
}
return _webView;