I have a problem with setting the height of an UIWebView
dynamically. The webview loads a product description which contains html. I want the UIWebView
to change its height based on the contents of the description. The parent scrollview should also change its height, but then based on the height of the UIWebView
.
Can anyone explain to me how I can achieve the desired behavior of my views?
This is my view hierarchy:
You have to add some code in the delegate method of UIWebView named webViewDidFinishLoad. Here is what you can do:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
CGRect frame = webView.frame;
frame.size.height = 1;
webView.frame = frame;
CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
frame.size = fittingSize;
webView.frame = frame;
NSLog(@"size: %f, %f", fittingSize.width, fittingSize.height);
yourScrollView.contentSize = webView.bounds.size;
}
The same thing can also be achieved using javascript to find the right height which is as follow:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
CGRect oldBounds = [[self webView] bounds];
CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.height"] floatValue];
NSLog(@"NEW HEIGHT %f", height);
[webView setBounds:CGRectMake(oldBounds.origin.x, oldBounds.origin.y, oldBounds.size.width, height)];
yourScrollView.contentSize = webView.bounds.size;
}
Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With