当UIWebView的宽度小于窗口宽度时,UIWebView中的网页无法正确自动调整大小。

3
我创建了一个简单的测试项目,只包含一个UIWebView,放在填满整个窗口的UIView上。当UIWebView的宽度与UIView相同时,一切都正常。当UIWebView的宽度小于容器的宽度时,水平滚动条会不规则地出现。我加载的网页是一个本地的html文件。它的宽度未设置,应该适合浏览器/UIWebView的宽度。
请帮忙解决。谢谢!
图片如下: The iPad simulator.

答案可能取决于您本地HTML文件中的标记。里面是否有任何指定宽度的内容(例如样式)? - Jim Blackler
不,只需要普通的<p>标签,例如:<p>这里是文本...</p> - Xenofex
4个回答

8

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.


2
非常好。第一种方法有时对我不起作用,特别是在使用UIWebView作为splitiviewcontroller的详细控制器时(不知道为什么)。第二种方法可以正常工作,但我只能使用以下JS字符串格式使其正常工作 @"document.getElementsByTagName('body')[0].style.width = '%1.0fpx'" - Felipe Sabino

4
上述解决方案对我也没起作用。问题是要让文本在适当的浏览器视图大小下换行,而不是缩小内容或允许滚动。
我的解决方法是通过执行一些巧妙的JavaScript来强制将视口插入HTML:
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];

您的里程可能会因为其他视口设置的需要而有所不同,或者如果您的网页已经有指定视口的元标记,则可能不需要。

这个JavaScript的想法来自于这个答案:如何在不使用jQuery append的情况下插入元标记?


不错的解决方案。像这样设置宽度在我使用iPad上嵌入式UIWebView横向模式时效果很好。但是,应该用逗号代替分号吧? - gavdotnet
另外,如果你想更新现有的视口标签而不是添加新的标签,可以使用以下替代方法:NSString *javascript = [NSString stringWithFormat:@"document.querySelector('meta[name=\"viewport\"]').setAttribute(\"content\", \"width=%d,initial-scale=1.0,maximum-scale=1.0,user-scalable=0\")", (int)authWebView.bounds.size.width]; - gavdotnet

1
您可以通过在中包含meta标签来为您的视口设置显式宽度,例如:
<meta name = "viewport" content = "width = 590">

请参阅Safari Web内容指南

同时,如果你想要让HTML适应iPhone和iPad(甚至是安卓设备),那么这并不好。另外,如果你考虑重复使用HTML,同时还要考虑到旧的安卓设备并且使用了position fixed(就像当前我的情况),你必须使用<meta name="viewport" content="width=device-width, user-scalable=no">。http://caniuse.com/#search=position - Felipe Sabino

0
尝试将网页视图模式设置为“填充缩放”。

如果UIWebView的“缩放页面以适应”模式为TRUE,则纵向显示的文本会比横向显示的文本小。因为这个视图在横向上更宽。这不是我期望的结果。 - Xenofex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接