【发布时间】:2012-03-23 11:45:30
【问题描述】:
所以我有一个 UIWebView 来显示静态 html 内容。
当我以纵向启动ViewController 并切换到横向时,它会正确调整内容的大小。
但是,当我以横向启动页面并切换到纵向时,它不会调整我的内容大小,并且需要滚动才能查看所有内容。
这是一个错误吗?是否有强制调整UIWebView 内容大小的解决方案?
【问题讨论】:
标签: ios ipad uiwebview rotation
所以我有一个 UIWebView 来显示静态 html 内容。
当我以纵向启动ViewController 并切换到横向时,它会正确调整内容的大小。
但是,当我以横向启动页面并切换到纵向时,它不会调整我的内容大小,并且需要滚动才能查看所有内容。
这是一个错误吗?是否有强制调整UIWebView 内容大小的解决方案?
【问题讨论】:
标签: ios ipad uiwebview rotation
您有 2 个选择:
将此添加到您的 html 文件的 HEAD 部分:
<meta name="viewport" content="width=device-width" />
或在方向改变时致电[myWebView reload]
【讨论】:
我遇到了类似的问题。我通过执行 javascript 代码来解决它,以在 UIViewController 完成旋转时生成一个更新页面方向的事件:
- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[webView stringByEvaluatingJavaScriptFromString:@"var e = document.createEvent('Events'); "
@"e.initEvent('orientationchange', true, false);"
@"document.dispatchEvent(e); "];
}
【讨论】:
我尝试了上面的其他建议,但它们无法在我加载的静态网页上运行。我尝试将此行添加到我的网页标题中
<meta name="viewport" content="width=device-width" />
但在我的设备上更改横向和纵向之间的方向后,它仍然没有调整页面宽度。然后我将此行添加到 func viewDidLoad() 并且它运行良好。我正在运行 iOS 11.4
myWebView.autoresizingMask = UIViewAutoresizing.flexibleWidth
【讨论】:
这个问题很老了,但这应该可以解决:
myWebView.scalesPageToFit = YES;
或者,如果您使用的是 Interface Builder,则可以勾选 Attributes Inspector 下显示“适合销售页面”的复选框。
希望对你有帮助。
【讨论】:
我最终使用了@Sergey Kuryanov 的第二种方法,因为第一种方法不适合我。我使用的是 UIWebView 的 loadHTMLString 方法,因此您将在代码中看到它,但您可以将其替换为您用于在 UIWebView 中加载数据的任何方法。
首先要做的是订阅轮播通知。为此,我按照@clearwater82 对这个问题的回答:How to detect rotation for a programatically generated UIView
我重写了他对 Swift 3 的回答,您可以在同一页面中找到它。
完成后,很容易使用loadHTMLString 在 UIWebView 中重新加载数据。我的方法是将 UIWebView 包装在自定义视图中,这样我也可以直接在自定义视图中处理一些 HTML 格式。这使得添加“reload-on-rotation”功能变得非常简单。这是我使用的代码,链接答案中的更多详细信息:
// Handle rotation
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(
self,
selector: #selector(self.orientationChanged(notification:)),
name: NSNotification.Name.UIDeviceOrientationDidChange,
object: nil
)
// Called when device orientation changes
func orientationChanged(notification: Notification) {
// handle rotation here
self.webView.loadHTMLString(self.htmlText, baseURL: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
UIDevice.current.endGeneratingDeviceOrientationNotifications()
}
我只想指出两点:
self.htmlText 是一个变量,其中包含我要加载的 HTML 文本,我添加到自定义视图中UIDevice.current.endGeneratingDeviceOrientationNotifications() 的使用适合我的情况,但可能不适合你的情况就是这样,干杯
【讨论】: