Iphone – UIWebView resize to fit Content

ios4iphoneuiwebview

Here is what I am trying to do,

I have a webView whose frame I am setting as

self.webView.frame = CGRectMake(0, Y,screenWidth,1);

the y coordinate is calculated based on the height of the other views that are added dynamically which works fine.

the screenWidth is set to 320 or 480 depending on device orientation which also works fine.

Now I want my webView to set it's width as the screenWidth and resize it's height alone to fit the content.

The content could be plainText which I load as

        NSData* data=[msgBody dataUsingEncoding:NSUTF8StringEncoding];             
        if (data) 
        [self.webView loadData:data MIMEType:@"text/plain" textEncodingName:@"UTF-8" baseURL:nil];  

or HTML which I load as

        [self.webView loadHTMLString:htmlMsgBody baseURL:nil]; 

In my WebViewDidFinishLoad method, I am doing this,

- (void)webViewDidFinishLoad:(UIWebView *)webview {

    CGRect frame = self.webView.frame;
    CGSize fittingSize = [self.webView sizeThatFits:CGSizeZero];
    frame.size = fittingSize;
    self.webView.frame = frame;

   CGFloat totalHeight = self.webView.frame.origin.y+self.webView.frame.origin.height+30;

    //the webView is scrolllocked and put on a scrollView so I do this

    [self.theScrollView setContentSize:CGSizeMake(screenWidth, totalHeight)];
}

My scrollView on which the webView is put can scroll horizontally. My webView is scrollLocked anyways. So I have to always keep my webView width to be the same as self.view.frame.size.width based on the device orientation and the webView width should change just to fit the content. I accordingly set the scrollView contentSize to allow vertical scrolling.

But the thing is that, the self.webView sizeThatFits method returns weird values and what happens is that when my screenWidth is 320 I get fittingSize.width as 408 and my content goes off screen horizontally and I am not able to show the content properly. Even if I forcibly set the frame of self.webView.frame.size.width = screenWidth, part of the content remains off screen.

How to deal with this situation?

Best Answer

According to the docs, size to fit:

Resizes and moves the receiver view so it just encloses its subviews.

This does not give you any information about fitting the webView into it's containing view. Is it possible that your webView is trying to display something wider than the screenWidth, and since you have it scroll locked, it is showing the whole width?