【发布时间】:2015-08-24 07:48:19
【问题描述】:
我找到了如何根据其内容计算动态 uiwebview 高度。我的代码是:
println("webViweDidFinish started")
var frame:CGRect = myWebView.frame
frame.size.height = 1
var fittingSize :CGSize = myWebView.sizeThatFits(CGSizeZero)
frame.size = fittingSize
myWebView.frame = frame
var contentsizeHeight = webView.scrollView.contentSize.height
var yCoordinateOfWebView = myWebView.frame.origin.y
var contentHeight: CGFloat = webView.scrollView.contentSize.height;
myScrollView.contentSize = CGSizeMake(self.view.frame.width, yCoordinateOfWebView + contentsizeHeight + labelAuthorOfArticle.frame.height) //
UIView.animateWithDuration(0.5, animations: {
self.heightConstraints.constant = fittingSize.height
self.myWebView.layoutIfNeeded()
self.myScrollContentView.layoutIfNeeded()
})
self.activityIndicator.stopAnimating()
如果我使用这种方法:
var height:NSString! = webView.stringByEvaluatingJavaScriptFromString("document.height;")
var heightInFloat = height.floatValue
如何将高度转换为 CGFloat?如您所见,我只能将其转换为浮动。
问题是当 webview 有太多图像时,高度计算错误。相反,当没有图像高度时计算正确。当我重新加载函数时,它第二次计算正确(带图像)。这是我正在加载的字符串内容:
class func formatContentText(inout text: NSString)-> NSString{
text = text.stringByReplacingOccurrencesOfString("src=\"", withString: "src=\"http://dixinews.kz")
var deviceWidth = "300"
text = "<html><head><meta name = \"viewport\" content = \"user-scalable=no, width=" + deviceWidth + " , maximum-scale=1.0\"><style>img{max-width:100%%;height:auto !important;width:auto !important;};</style></head><body>" + text + "</body></html>"
return text
}
【问题讨论】:
-
你混合了几个概念。首先,您设置框架并更新约束。要么您使用自动布局,那么您必须更改高度约束常量,或者您不使用,那么您不需要更新约束。其次,您使用两种不同的策略(使用 sizeThatFits 技巧和使用 JS)确定内容高度,并用第二种方法覆盖第一种。我建议先清理代码。
-
你能再看一遍吗,我清除了代码