【发布时间】:2019-06-16 23:44:46
【问题描述】:
我正在尝试获取我的WKWebview 内容的正确高度和宽度,以将 webview 容器高度设置为 webview 内容。
我已经尝试了很多关于堆栈溢出的解决方案。
使用此代码,容器具有正确的高度,但是 webview 的宽度太大(好像 webview 被缩放了)
override func viewDidLoad() {
let webConfiguration = WKWebViewConfiguration()
let customFrame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: 0.0, height: self.viewForWebview.frame.size.height))
self.webView = WKWebView (frame: customFrame , configuration: webConfiguration)
webView.translatesAutoresizingMaskIntoConstraints = false
self.viewForWebview.addSubview(webView)
NSLayoutConstraint.activate([
self.webView.topAnchor.constraint(equalTo: self.viewForWebview.topAnchor),
self.webView.bottomAnchor.constraint(equalTo: self.viewForWebview.bottomAnchor),
self.webView.leadingAnchor.constraint(equalTo: self.viewForWebview.leadingAnchor),
self.webView.trailingAnchor.constraint(equalTo: self.viewForWebview.trailingAnchor)
])
webView.uiDelegate = self
webView.navigationDelegate = self
webView.scrollView.isScrollEnabled = false
let bodyHtml = "<html><head><meta name=\"viewport\" content=\"initial-scale=1.0\" />" + htmlString + "</body></html>";
webView.loadHTMLString(bodyHtml, baseURL: Bundle.main.resourceURL)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.heightWebviewConstraint.constant = self.webView.scrollView.contentSize.height
self.view.setNeedsLayout()
self.view.setNeedsUpdateConstraints()
}
除了添加<head>标签,我也尝试使用evaluateJavaScript,但是在这种情况下,高度的容器太大了,而webview的宽度也太大了。
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
if complete != nil {
self.webView.evaluateJavaScript("document.body.offsetHeight", completionHandler: { (height, error) in
self.heightWebviewConstraint.constant = height as! CGFloat
self.view.setNeedsLayout()
self.view.setNeedsUpdateConstraints()
})
}
})
}
我还尝试添加特定的css样式(没有viewport和没有evaluateJavaScript),在这种情况下webview的宽度还可以,但是高度的容器太小(我的webview在顶部和底部被裁剪)。
let bodyHtml = "<html><head> <style> img { width:auto; height:auto; max-width:100%; </style></head><body>" + htmlString + "</body></html>"
我迷失了所有这些解决方案。
【问题讨论】:
标签: ios swift webview height wkwebview