views:

515

answers:

2

Hey.

I'm trying to use a UIWebView for displaying content higher than the screen of the iPhone, without needing to scroll in the webView itself.

The webView is placed under a UIScrollView in IB with some other objects that I want the scrollView to scroll up and down with the UIWebView.

I know you can do this with a UITextView (CGRect frame = _textView.frame; frame.size.height = _textView.contentSize.height; _textView.frame = frame;), but the UIWebView does not inherit from UIScrollView and does therefore not contain the contentSize-property.

I'd really like to keep it a UIWebView, because the data I get is in HTML-blocks.

Thank you!

+3  A: 

I think the only way you'll be able to do this is to use some javascript to get the size of the web page and adjust the size of the UIWebView control.

Something like the following should do the trick

int content_height = [[theWebView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"] integerValue];
CGRect rect = theWebView.frame;
rect.size.height = content_height;
theWebView.frame = rect;

You may need to add some sort of fudge factor to the content height.

Daniel
Nope, this only seems to hide the UIWebView.. Good idea, though.
Emil
content_height = 0.
Emil
You might need to wait until the UIWebView has finished loading your content before the above code will give you what you want. I have used a variation on the above code successfully in some web apps to resize embedded IFRAME tags.
Daniel
@Daniel That did the trick :)
Emil
+1  A: 

In fact, no Javascript is needed! In UIView there is a nice method:

- (CGSize)sizeThatFits:(CGSize)size

You pass it anything (not really meaningful here), and it returns the size it'd like to be, using its content (subviews, etc) to compute the size.

Of course, since content loading in a UIWebView in asynchronous, you should do this after the webview has loaded, for instance in the UIWebViewDelegate method:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    CGSize size = [webView sizeThatFits: CGSizeMake(1.0f, 1.0f)]; // Pass about any size
    CGRect frame = webView.frame;
    frame.size.height = size.height;
    webView.frame = frame;
}

Et voila!

jv42
I don't know why, but this didn't work. Sorry.
Emil
Specification: This did kind of work, but not when the webView contains images, probably because these aren't fully loaded at the time.
Emil
Ah... so UIWebView notify when the base HTML is loaded, not the whole page. Anyway, if your images change your layout, your pages are not W3C compliant (should contain size in the img tag) :p
jv42
Not my webpages ;) Thanks, though.
Emil