UIWebView sizeToFit() Smaller

1.5k views Asked by At

It appears that using sizeToFit() on a UIWebView does not change the size to be smaller, only larger. This is some set-up code:

var scrollView: UIScrollView!
var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    scrollView = UIScrollView()
    scrollView.frame = CGRect(x: 50.0, y: 50.0, width: 800.0, height: 1200.0)

    webView = UIWebView()
    webView.frame = CGRect(x: 50.0, y: 50.0, width: 800.0, height: 1.0)
    webView.scrollView.scrollEnabled = false
    webView.delegate = self
    webView.scalesPageToFit = false
    webView.loadHTMLString("Test", baseURL: nil)

    self.view.addSubview(scrollView)
    scrollView.addSubview(webView)
}

This is my test code. It changes the size of the content to be VERY LARGE after 3 seconds, then VERY SMALL after another 3 seconds:

    dispatch_after_delay_main(3) {

        self.webView.loadHTMLString("Test Test Test Test ", baseURL: nil)
        // Much longer string abbreviated here

        dispatch_after_delay_main(3, block: {

            self.webView.loadHTMLString("Test", baseURL: nil)

        })
    }

This is called after the HTML is loaded. The goal is to change the size of the webView based on the size of its content. Note: I've done this with both .sizeToFit() and sizeThatFits() with the same size result.

func webViewDidFinishLoad(webView: UIWebView) {

    webView.frame.size.height = 0.0 // Just in case
    webView.sizeToFit()

}

I've omitted the print statements at the end of webViewDidFinishLoad(webView: UIWebView) but they output the size growing, but not decreasing. In other words, it will grow, but then once "Test" is loaded, it does not decrease in size.

(800.0, 1.0)  // "Test" (before sizeToFit() called)
(800.0, 1976.0) // "Test Test .... Test "
(800.0, 1976.0) // "Test"
1

There are 1 answers

4
Rafael Passos On

do you need the webview embedded on a scrollView? I think not.

Try to change your HTML string to "<div id='main-html'>Your text</div>" and then on the webViewDidFinishLoad delegate function you will do these things:

First, you get the content height with:

var result : Float = NSString (webView.stringByEvaluatingJavaScriptFromString("document.getElementById('main-html').offsetHeight").floatValue

Second, change the webview height with the result value.

And tries to change the height of webView.scrollView.contentSize using the same result value.

Finally, use the webView.sizeToFit()

Cheers

EDIT:

As you said, you can use:

func webViewDidFinishLoad(webView: UIWebView) {

    webView.frame.size.height = 1.0 // Value needs to be > 0.0 and < of the current height
    webView.sizeToFit()

}