首页 > 解决方案 > 改变方向时无法自动旋转

问题描述

我正在使用 Swift4 使用 Xcode9 开发一个应用程序,它最初是为 iPad 设计的,但现在也需要在手机上运行。我需要将手机锁定为纵向,iPad 保持纵向/横向。

在使用 shouldautorotate 函数并根据设备返回 true 或 false 之前,我已经完成了此操作,如下所示。

override func shouldAutorotate() -> Bool {
   return false
}

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
   return UIInterfaceOrientationMask.all
}

但是,当我更改方向时,它不会触发。这是另一种折旧的方法吗?如果是,我现在如何限制方向?

标签: swiftxcodeorientationshouldautorotate

解决方案


如果您的视图控制器嵌入到UINavigationControllerorUITabBarController中,则会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
    }        
}

推荐阅读