Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIWebView - Autoresize so that no scrolling (in the webView itself) is needed

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

The UIWebView is placed as a subview to a UIScrollView, along with some other objects that I want the UIScrollView to scroll up and down with the UIWebView.

I know you can do this with a UITextView like this:

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!

like image 508
Emil Avatar asked Jun 04 '10 21:06

Emil


2 Answers

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!

like image 141
jv42 Avatar answered Oct 15 '22 07:10

jv42


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.

like image 7
Daniel Avatar answered Oct 15 '22 07:10

Daniel