views:

177

answers:

2

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.

A: 

AFAIK you can use [webView sizeThatFits:CGSizeZero] to figure out it's content size.

Rengers
A: 

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.

- (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);
}

I should point out there's another approach (http://stackoverflow.com/questions/745160/how-to-determine-uiwebview-height-based-on-content-within-a-variable-height-uita – thanks @GregInYEG) using JavaScript. Not sure which solution performs better.

Of two hacky solutions I like this one better.

Ortwin Gentz