WKWebView 加载HTML高度不精确,留有空白的解决方案

原文网址:https://www.jianshu.com/p/445766cb058c

1.查找img标签,添加宽度设置

    NSString *result = [NSString stringWithFormat:@"<%@ %@",@"img",@"style='display: block; max-width: 100%;'"];

2.将设置的img标签插入到HTML数据中,对获取的HTML数据进行格式组装

NSString*contentStr = additionalInfo[@"description"]; //原来获取到的html字符串

    contentStr = [contentStr stringByReplacingOccurrencesOfString:@"
%@
", contentStr];

3.wkwebview加载HTML

[_webView loadHTMLString:safeString(htmlStr) baseURL:nil];

4.获取HTML高度

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {

__weak typeof(self) weakSelf = self;
    //获取内容实际高度(像素)@"document.getElementById(\"content\").offsetHeight;"
    [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result,NSError * _Nullable error) {
        // 此处js字符串采用scrollHeight而不是offsetHeight是因为后者并获取不到高度,看参考资料说是对于加载html字符串的情况下使用后者可以,但如果是和我一样直接加载原站内容使用前者更合适
        //获取页面高度,并重置webview的frame
        CGFloat height = [result floatValue];
        NSLog(@"%f", height);
        dispatch_async(dispatch_get_main_queue(), ^{
            //这里用model缓存的高度 可根据自己的代码修改
            if (weakSelf.imageDetailModel.cellheight != height + 1) {

            weakSelf.imageDetailModel.cellheight = height + 1;
            
            //回调刷新cell 重置高度
            if (weakSelf.imageDetailModel.cellheight > 20) {
                if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(cell:didLoadFinish:)]) {
                    [self.delegate cell:weakSelf didLoadFinish:weakSelf.webView];
                }
            }
          }
        });
    }];

    NSLog(@"结束加载");
}

 

你可能感兴趣的:(iOS,webview,行高,oc,ios)