美文网首页
WKWebView获取网页内容高度

WKWebView获取网页内容高度

作者: satisfying | 来源:发表于2021-09-28 16:21 被阅读0次
    //实现代理WKNavigationDelegate

        webview.scrollView.isScrollEnabled=false

        let config=WKWebViewConfiguration.init()
        config.selectionGranularity = .dynamic
        config.allowsInlineMediaPlayback=false
        let preferencs=WKPreferences.init()
        preferencs.javaScriptEnabled=true
        preferencs.javaScriptCanOpenWindowsAutomatically=true
        config.preferences=preferencs
//        NSString *htmlString = @"<style>body{margin:0}</style><img src=store_bg.jpg width=\"100%\"/>";
        let str="<style>body{margin:0}</style><img src=\(commodity.productDescUrl[0]) width=\"100%\"/>"
        webview.loadHTMLString(str, baseURL: nil)//这里加载的是一个图片
        webview.navigationDelegate=self
 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        var webheight = 0.0
              
              // 获取内容实际高度
              self.webview .evaluateJavaScript("document.body.scrollHeight") { [unowned self] (result, error) in
                  
                  if let tempHeight: Double = result as? Double {
                      webheight = tempHeight//这里是获取到内容高度
                      print("webheight: \(webheight)")
                  }
                  //更新高度
                  DispatchQueue.main.async { [unowned self] in
   
                    let height=webheight
                    webview.snp.makeConstraints { (make) in
                        make.height.equalTo(height)
                    }
                  }
              }
    }

相关文章

网友评论

      本文标题:WKWebView获取网页内容高度

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