views:

564

answers:

3

I need adjust the height and width of UIWebView so that the whole text is displayed within the view and the user need not scroll to read the text.

Does anyone has any idea how to get it?

A: 

There are no special provisions on UIWebView for resizing to fit the content. You could set the scalesPageToFit property to YES to scale the content down, or you could make the view large enough to fit most reasonably sized pages. I infer from your question that you're displaying content you're in control of. If not, I'm not sure there's an easy programmatic way to achieve what you want.

warrenm
Thaks a ton for the answer!!!yeah, tried with scalesPageToFit property set to YES.... but it shrinks the content too much and is not readable...
Looks like the UIWebView+SFHFStringMetrics category suggested above may be useful. It invokes some Javascript on the rendered document to determine its dimensions.
warrenm
+3  A: 
webView.scalesPageToFit = YES;

See also: UIWebView+SFHFStringMetrics

Can Berk Güder
+1  A: 

Hopefully this will point you in the right direction.

By calling the stringByEvaluatingJavaScriptFromString: method on the UIWebView you can execute JavaScript from your application in the UIWebView.

// get the height of your content
[webview stringByEvaluatingJavaScriptFromString:@"document.getElementById('id_of_content_container').offsetHeight;"];

// get the width of your content
[webview stringByEvaluatingJavaScriptFromString:@"document.getElementById('id_of_content_container').offsetHeight;"];

The above will return an NSString object with the width and height of whatever element you pass into the getElementById function. With that information you should be able to resize the UIWebView to accommodate your content. An example:

CGRect frame = webView.frame;
frame.size.width = 100;
webView.frame = frame;

You may also need to reset scalesPageToFit again to get the content to readjust to the new frame size.

Another option would be to detect window.height and window.width on the HTML side and use JavaScript to adjust the content to fit within the aspects of the UIWebView.

Intelekshual
Like the answers have pointed out, I don't think you'll be able to do this on the application side. You'll need to write some JavaScript on the HTML side that determines the width/height of the window and compares it with the width/height of the content container and adjusts accordingly.
Intelekshual