计算 UIWebView 和 WKWebView的高度

2018-04-27  本文已影响0人  shouyu

UIWebView

detailWeb = UIWebView.init(frame: CGRect.init(x: 0, y: 0, width: Href.screenWidth(), height: 1))

detailWeb?.loadHTMLString(html, baseURL: URL.init(string: kBaseUrl))
detailWeb?.delegate=self

func webViewDidFinishLoad(_ webView: UIWebView) {
     //获取到webview的高度
let webHeight = (self.detailWeb?.stringByEvaluatingJavaScript(from: "document.body.offsetHeight"))! as NSString
//重置坐标
  
 }

WKWebView

//解决加载完一片空白的问题
        let header = "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><meta  name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\"/><meta name=\"apple-mobile-web-app-capable\" content=\"yes\"><meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\"><link rel=\"stylesheet\" type=\"text/css\" /><style type=\"text/css\"> </style></head>"
        let html = "<html>" + header + "<body style='width:100%;background-color:white;padding:0px;margin:0px;display:block;'>" + body + "</body></html>"

        detailWeb = WKWebView.init(frame: CGRect.init(x: 0, y: 0, width: Href.screenWidth(), height: 1))
        detailWeb?.loadHTMLString(html, baseURL: URL.init(string: kBaseUrl))
        detailWeb?.navigationDelegate=self

       func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        self.detailWeb?.evaluateJavaScript("document.body.offsetHeight;", completionHandler: { (result, err) in
            print(result as Any)
            let webHeight = result as! CGFloat
//重置坐标
            self.detailWeb?.frame=CGRect.init(x: (self.detailWeb?.frame.origin.x)!, y: (self.detailWeb?.frame.origin.y)!, width: Href.screenWidth(), height: webHeight)
            self.tableView.reloadData()
        })
    }

参考文章 https://www.jianshu.com/p/4565c53035ed

上一篇下一篇

猜你喜欢

热点阅读