暂时将应用限制为特定方向

时间:2015-12-02 21:35:09

标签: ios uiviewcontroller uiinterfaceorientation

我有一个支持所有方向的应用,但在某些情况下,我想暂时将其限制为仅限肖像。它不是只需要肖像的视图控制器和可以是任何方向的视图控制器的组合,而是我想在用户单击屏幕上的按钮时禁用方向更改,而视图控制器保持不变

在寻找限制UIViewController的UI方向的方法时,弹出的方法为supportedInterfaceOrientations()preferredInterfaceOrientationForPresentation()。两者都不适合我:

  • supportedInterfaceOrientations()在加载视图时只运行一次,因此即使我将其返回值设置为条件,它也不会在条件更改后运行。
  • 我的视图控制器显示在导航堆栈中,而不是模态,因此preferredInterfaceOrientationForPresentation()根本不会运行。

有没有办法达到我想要的效果?

1 个答案:

答案 0 :(得分:1)

我将假设您的视图控制器位于导航控制器中。如果没有导航控制器,只要设备旋转,就会调用supportedInterfaceOrientations()。但是,当嵌入在导航控制器中时,导航控制器决定视图控制器是否应该旋转。 (见下面的例子) enter image description here enter image description here

你需要做什么?在自定义UINavigationController中实现supportedInterfaceOrientations(),如下所示:

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    if self.topViewController is RootViewController {
        return .Portrait
    } else {
        return .All
    }
}

这是this的重复问题,但我没有看到一个快速的例子。对于你想要留在肖像中的任何类,只需将RootViewController替换为类名。