Resizing a UIWebView to fit with a fixed width

Formatting ScreenshotUIWebView is great for displaying hightly formated content, but sizing the frame correctly can be tough at times. Recently, I was using a UIWebView to display formated content and I needed to resize it display all of it's contents. The standard way to automatically resize a UIView to fit its contents is to call sizeToFit. Calling sizeToFit on the UIWebView in the -(void)webViewDidFinishLoad:(UIWebView *)webView UIWebViewDelegate method works nicely… almost.

My problem was that I wanted the width to be fixed and change only the height but sizeToFit automatically changes both, causing the content to run off the edge of the screen.

However, there is a neat little trick.

By calling the UIWebView's& stringByEvaluatingJavaScriptFromString method it is possible to interact with the content of the UIWebView. From there it is easy to get the content size and resize the UIWebView's frame accordingly.

    - (void)webViewDidFinishLoad:(UIWebView *)webView {
    	CGFloat contentHeight = [[webView stringByEvaluatingJavaScriptFromString:
    		"document.documentElement.scrollHeight"] floatValue];
    	webView.frame = CGRectMake(webView.frame.origin.x, webView.frame.origin.y, 
    		webView.frame.size.width, contentHeight);

And away you go.