Tom Tom - 11 months ago 150
Swift Question

UIWebView content height

I've been looking around and wasnt able to see any swift related ways to do this. I'm trying to get my UIWebViews height to be dynamic. I have a UIWebView that loads data using the loadHtmlString function.The thing is that I am loading the data from an sqlite database, each time I load a different string with different length and naturally the web view obtains different height.
Now I need to know how to make the UIWebView that exact height in order to load my next content right under the webView. This is what I have so far

var jobSkillView = UIWebView(frame: CGRectMake(-5, 480.0, screenWidth, 300.0))
jobSkillView.loadHTMLString("<html><body p style='font-family:arial;font-size:16px;'>" + jobSkills + "</body></html>", baseURL: nil)
jobSkillView.backgroundColor = UIColor.whiteColor()
jobSkillView.opaque = false
jobSkillView.scrollView.scrollEnabled = true
jobSkillView.scrollView.bounces = true

I found something like this on stack saying but not sure how to link it to the UIWebView frame

func webViewDidFinishLoad(jobSkillView : UIWebView){
// Change the height dynamically of the UIWebView to match the html content
var jobSkillViewFrame: CGRect = jobSkillView.frame
jobSkillViewFrame.size.height = 1
jobSkillView.frame = jobSkillViewFrame
var fittingSize: CGSize = (jobSkillView.sizeThatFits(CGSizeZero))
jobSkillViewFrame.size = fittingSize
// webViewFrame.size.width = 276; Making sure that the webView doesn't get wider than 276 px
jobSkillView.frame = jobSkillViewFrame

var jobSkillViewHeight = jobSkillView.frame.size.height

Answer Source

So this is a really great function you wrote there, OP!
Here is just a shorter, more elegant version of your code:

//make sure to declare the delegate when creating your webView (add UIWebViewDelegate to class declaration as well)
myWebView.delegate = self

func webViewDidFinishLoad(webView: UIWebView) {
     webView.frame.size.height = 1
     webView.frame.size = webView.sizeThatFits(CGSizeZero)

For Swift 3

myWebView.delegate = self

func webViewDidFinishLoad(webView: UIWebView) {
     webView.frame.size.height = 1
     webView.frame.size = webView.sizeThatFits(CGSize(widht:0, height:0))