swift - 改变方向时无法自动旋转
问题描述
我正在使用 Swift4 使用 Xcode9 开发一个应用程序,它最初是为 iPad 设计的,但现在也需要在手机上运行。我需要将手机锁定为纵向,iPad 保持纵向/横向。
在使用 shouldautorotate 函数并根据设备返回 true 或 false 之前,我已经完成了此操作,如下所示。
override func shouldAutorotate() -> Bool {
return false
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.all
}
但是,当我更改方向时,它不会触发。这是另一种折旧的方法吗?如果是,我现在如何限制方向?
解决方案
如果您的视图控制器嵌入到UINavigationController
orUITabBarController
中,则会shouldAutorotate()
从它们中查询,因为此容器是最顶层的视图控制器。在 iOS 更新之后,它不会要求包含视图控制器是否需要旋转。因此,您可以使用自定义子类并在运行时创建它或在情节提要中提供自定义类:
import UIKit
class CustomNavigationController: UINavigationController {
override var shouldAutorotate: Bool {
return self.viewControllers.last?.shouldAutorotate ?? true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return self.viewControllers.last?.supportedInterfaceOrientations ?? .all
}
}
推荐阅读
- c# - TextBox 内容未绑定到源 WPF DataGrid
- r - 在 R 中存储大型数据帧的最佳格式之一是什么?
- webpack - 将 CKEditor 集成到 Shopware 6
- sql - 如果我添加一个标准,检查总数百分比的简单方法
- rust - 如何在锈火箭响应中将身体响应为 T
- excel - 我在执行 GETPIVOTDATA 公式时收到错误消息
- flutter - 我们如何在颤动的导航栏上实现悬停效果?
- nginx - CloudFlare 缓存问题
- reactjs - 将 Webpack React 库捆绑为 ESM 模块 - 在非对象上调用 Object.defineProperty
- angular - 提交时有撇号时WebStorm将单引号更改为双引号