Reputation: 591
I made a simple test project containing only one UIWebView on a UIView filled the window. When the UIWebView's width is the same as UIView, everything works well. When the UIWebView's width is less than the container's width, horizontal scrollbar appears irregularly. The webpage I load is a local html file. The width is not set so it should fit the browser/UIWebView's width.
Please help. Thanks.
Upvotes: 3
Views: 7605
Reputation: 938
method 1. webView.scalePageToFit = YES
, but when the width of the webView changes, the font size of the webpage will change accordingly, to solve this, you can try method 2:
method 2. dynamically set the width of the webView in your Objective-C code, so that when the width of the UIWebView is changed, change the width of the HTML webpage by calling a javascript script.
int webViewWidth = isPortraitOrLandscape ? 768:1024; // the dynamic width of the webView
NSString *javascript = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.width = '%dpx'", webViewWidth];
[webView stringByEvaluatingJavaScriptFromString:javascript];
by doing this, the width of the webView could be matched with the actual HTML webpage.
Upvotes: 8
Reputation: 3762
The above solutions didn't quite work for me either. The question wants the text to wrap at the appropriate browser view size, not scale the content down, nor allow scrolling.
My fix was to force a viewport into the html by executing some sneaky javascript:
javascript = [NSString stringWithFormat:@"var viewPortTag=document.createElement('meta'); \
viewPortTag.id='viewport'; \
viewPortTag.name = 'viewport'; \
viewPortTag.content = 'width=%d; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;'; \
document.getElementsByTagName('head')[0].appendChild(viewPortTag);" , (int)authWebView.bounds.size.width];
[authWebView stringByEvaluatingJavaScriptFromString:javascript];
Your milage may vary depending on other viewport settings you may or may not need, or if your webpage already has a meta tag specifying the viewport.
The javascript idea came from this answer: How to insert metatag without using jquery append?
Upvotes: 4
Reputation: 17918
You can set an explicit width for your viewport by including a meta tag in your <head>
like this:
<meta name = "viewport" content = "width = 590">
See the Safari Web Content Guide.
Upvotes: 1