美文网首页汽车公司可能用到的知识点
各种view嵌入WKWebView 计算高度 和自适应布局

各种view嵌入WKWebView 计算高度 和自适应布局

作者: 林希品 | 来源:发表于2023-01-09 15:51 被阅读0次

    OC

    NSString *htmlHeader = @"<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"><style>img{max-width: 100%; width:auto; height:auto!important;}</style></head>";
    NSString *htmlStr = [NSString stringWithFormat:@"<html>%@<body>%@</body></html>",htmlHeader,descriptionDetailStr];
    [self.webView loadHTMLString:htmlStr baseURL:nil];
    
    - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
        // 方法一
        [webView evaluateJavaScript:@"document.body.offsetHeight" completionHandler:^(id _Nullable result,NSError * _Nullable error){
            if (self.webViewHeight) {
                self.webViewHeight([result floatValue] + 20);
            }
            self.loadedBOOL = YES;
            webView.scrollView.scrollEnabled = NO;
            /**webView*/
            [webView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo([result floatValue] + 10);
            }];
            [self.tableView beginUpdates];
            [self.tableView endUpdates];
        }];
    }
    

    swift

     var head = "<head>" +
                    "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">" +
                    "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                    "<style>img{max-width: 100%; width:auto; height:auto!important;}</style>" +
                    "</head>"        
            let cellModel:GoodsDetail_goodsVoModel = model.cellModel as! GoodsDetail_goodsVoModel
            let url:NSString = "<html>\(head)<body>\(cellModel.description)</body></html>" as NSString
            self.webView.loadHTMLString(url as String, baseURL: nil)
    
    extension <#view#>: WKNavigationDelegate {
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            webView.evaluateJavaScript("document.body.scrollHeight") { (Result, error) in
                //页面高度
                let height = Result as? Double
                webView.snp.updateConstraints { (make) in
                    make.height.equalTo(height!)
                }
                webView.scrollView.isScrollEnabled = false;
        //        WKWebView
                self.tableV?.beginUpdates()
                self.tableV?.endUpdates()
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:各种view嵌入WKWebView 计算高度 和自适应布局

        本文链接:https://www.haomeiwen.com/subject/ottmcdtx.html