2015-06-09 62 views
0

我发现如何根据其内容计算动态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 
} 
+0

你在混合几个概念。首先,您设置框架并更新约束。要么你使用自动布局,那么你必须改变高度约束常数,否则你不需要更新约束。其次,您使用两种不同的策略(使用sizeThatFits技巧和使用JS)确定内容高度,并用第二种策略覆盖第一个策略。我建议先清理代码。 –

+0

你能再看一遍,我清除了代码 –

回答

0

我用JavaScript的方法。这里是我的代码:

func webViewDidFinishLoad(webView: UIWebView) { 





    var frame:CGRect = myWebView.frame 



    // javascript 
    var height:NSString! = webView.stringByEvaluatingJavaScriptFromString("document.height;") 

    var heightInFloat = height.floatValue // convert to float 

    var heightINCGFloat = CGFloat(heightInFloat) convert to cgfloat 

    frame.size.height = heightINCGFloat //set heigh 

    myWebView.frame = frame // set frame 

    myWebView.scrollView.contentSize.height = myWebView.frame.height 

    var contentsizeHeight = webView.scrollView.contentSize.height 

    var yCoordinateOfWebView = myWebView.frame.origin.y 

    myScrollView.contentSize = CGSizeMake(self.view.frame.width, yCoordinateOfWebView + contentsizeHeight + labelAuthorOfArticle.frame.height) // 

    UIView.animateWithDuration(0.5, animations: { 
     self.heightConstraints.constant = heightINCGFloat 

     self.myWebView.layoutIfNeeded() 

     self.myScrollContentView.layoutIfNeeded() 

    }) 

    self.activityIndicator.stopAnimating() 


} 
+0

document.height不存在 –

+0

也许经过一些更新后,它已被弃用,试着谷歌你可以使用,而不是。 –

相关问题