我發現如何根據其內容計算動態uiwebview高度。我的代碼是:用圖像計算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)確定內容高度,並用第二種策略覆蓋第一個策略。我建議先清理代碼。 –
你能再看一遍,我清除了代碼 –