How to determine the content size of a UIWebView?

Ortwin Gentz picture Ortwin Gentz · Oct 14, 2010 · Viewed 126.3k times · Source

I have a UIWebView with different (single page) content. I'd like to find out the CGSize of the content to resize my parent views appropriately. The obvious -sizeThatFits: unfortunately just returns the current frame size of the webView.

Answer

Ortwin Gentz picture Ortwin Gentz · Oct 14, 2010

It turned out that my first guess using -sizeThatFits: was not completely wrong. It seems to work, but only if the frame of the webView is set to a minimal size prior to sending -sizeThatFits:. After that we can correct the wrong frame size by the fitting size. This sounds terrible but it's actually not that bad. Since we do both frame changes right after each other, the view isn't updated and doesn't flicker.

Of course, we have to wait until the content has been loaded, so we put the code into the -webViewDidFinishLoad: delegate method.

Obj-C

- (void)webViewDidFinishLoad:(UIWebView *)aWebView {
    CGRect frame = aWebView.frame;
    frame.size.height = 1;
    aWebView.frame = frame;
    CGSize fittingSize = [aWebView sizeThatFits:CGSizeZero];
    frame.size = fittingSize;
    aWebView.frame = frame;

    NSLog(@"size: %f, %f", fittingSize.width, fittingSize.height);
}

Swift 4.x

func webViewDidFinishLoad(_ webView: UIWebView) {
    var frame = webView.frame
    frame.size.height = 1
    webView.frame = frame
    let fittingSize = webView.sizeThatFits(CGSize.init(width: 0, height: 0))
    frame.size = fittingSize
    webView.frame = frame
}

I should point out there's another approach (thanks @GregInYEG) using JavaScript. Not sure which solution performs better.

Of two hacky solutions I like this one better.