Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Resize UIWebView after didFinishLoad (content should fit without scrolling)

I am absolutely unable to resize my UIWebView.

My UIWebView is declared in .h and in connected in IB. The height in IB is 110. But the height of my text is about 1500. Now I'd like to change the height so the full text is readable without scrolling.

What code does resize my UIWebView in webViewDidFinishLoad? Can't find ANYTHING that works.

like image 961
filou Avatar asked Dec 13 '12 10:12

filou


3 Answers

The UIScrollView property is available for UIWebView starting in iOS 5. You can use that to resize your view by implementing the webViewDidFinishLoad: message in your delegate, like this:

-(void)webViewDidFinishLoad:(UIWebView *)webView {
    CGRect newBounds = webView.bounds;
    newBounds.size.height = webView.scrollView.contentSize.height;
    webView.bounds = newBounds;
}
like image 128
John Stephen Avatar answered Oct 29 '22 03:10

John Stephen


Have you tried: this answer?

[Edit]

Some guys say this is working:

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

// Change the height dynamically of the UIWebView to match the html content
CGRect webViewFrame = webView.frame;
webViewFrame.size.height = 1;
webView.frame = webViewFrame;
CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
webViewFrame.size = fittingSize;
// webViewFrame.size.width = 276; Making sure that the webView doesn't get wider than 276 px
webView.frame = webViewFrame;

float webViewHeight = webView.frame.size.height;
}

This is untested by me but 70 people voted ^ to this answer and its recommend to set sizeTahtFits:CGSizeZero like a reset of your frame.size

and some people use JavaScript to fix this:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *string = [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"body\").offsetHeight;"];
CGFloat height = [string floatValue] + 8;
CGRect frame = [_webView frame];
frame.size.height = height;
[_webView setFrame:frame];

if ([[self delegate] respondsToSelector:@selector(webViewController:webViewDidResize:)])
{
    [[self delegate] webViewController:self webViewDidResize:frame.size];
}
}
like image 43
zero3nna Avatar answered Oct 29 '22 01:10

zero3nna


as answered by john and eric above, this piece of code works.

-(void)webViewDidFinishLoad:(UIWebView *)webView {
    CGRect newBounds = webView.bounds;
    newBounds.size.height = webView.scrollView.contentSize.height;
    webView.bounds = newBounds;
}

however while trying with this code i found out it returns me with a proper webview but improper origin, if thats the case for anyone, simply reset with this code

webView.frame=CGRectMake(webView.frame.origin.x, webView.center.y, webView.frame.size.width, webView.frame.size.height);

The y-axis is set and you get the webView as you wanted.

like image 45
Maniac One Avatar answered Oct 29 '22 01:10

Maniac One