如何在swift上禁用和启用自动旋转?

时间:2015-05-07 19:49:50

标签: ios swift rotation

在一般设置中,我允许纵向和风景左侧,景观控制模式。我想关闭横向模式。在viewController上我写了这段代码:

override func shouldAutorotate() -> Bool {

        return false

}

但是,自动旋转忽略此功能。如何在swift上禁用和启用自动旋转? IOS编程

5 个答案:

答案 0 :(得分:9)

它可能是正确的代码,但不在右侧的View Controller中。例如,如果视图控制器嵌入在UINavigationController中,导航控制器仍然可以旋转,从而导致视图控制器仍然旋转。这实际上取决于你的具体情况。

答案 1 :(得分:3)

我有同样的问题,我已经解决了这个问题。

请 -

info - >自定义ios目标属性 - >支持接口Orinetations。并删除![删除 - 横向(左主页按钮),横向(右主页按钮),横向(顶部主页按钮)] [1]

这会对你有所帮助

答案 2 :(得分:3)

您可以通过创建UINavigationController的子类来实现,并在其中覆盖should AutoRotate函数,然后

  • 为要禁用自动旋转的viewControllers返回false
  • 对于您想要自动旋转的viewControllers返回true

    import UIKit    
    
    class CustomNavigationController: UINavigationController {
    
    override func shouldAutorotate() -> Bool {
        if !viewControllers.isEmpty {
            // Check if this ViewController is the one you want to disable roration on
            if topViewController!.isKindOfClass(ViewController) {               //ViewController is the name of the topmost viewcontroller
    
                // If true return false to disable it
                return false
            }
        }
        // Else normal rotation enabled
        return true
       }
    }
    

如果要在整个导航控制器中禁用自动旋转,请删除if条件并始终返回false

答案 3 :(得分:0)

扩展了Josh Gafni的答案和user3655266,该概念还扩展到了视图控制器。

如果我们有一个UIViewController,它是视图层次结构中另一个UIViewController的子级,则由于父级的控制器可能仍返回 true,因此仍可能会将子级的shouldAutorotate()覆盖为 false 。同样重要的是要知道,即使正在显示子VC,仍会调用父级的shouldAutoRotate函数。因此控件应该位于此处。

快速5

class ParentViewController:UIViewController{ 
    override func shouldAutorotate() -> Bool {
        // Return an array of ViewControllers that are children of the parent
        let childViewControllersArray = self.children
        if childViewControllersArray.count > 0 {
            // Assume childVC is the ViewController you are interested in NOT allowing to rotate
            let childVC = childViewControllersArray.first
            if childVC is ChildViewController {
            return false
            }
        }
        return true 
    }
}

**也可以这样做,仅允许某些手机方向**

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        // This function is called on the parent's controller whenever the child of this parent is trying to rotate
        let childrenVCArray = self.children
        if childrenVCArray.count > 0 {
            // assuming the array of the first element is the current childVC
            let topMostVC = childrenVCArray[0]
            if topMostVC is ChildViewController {
                // Assuming only allowing landscape mode
                return .landscape
            }
        }
        // Return portrait otherwise
        return .portrait

    }

答案 4 :(得分:0)

我不确定在 2021 年 swift 5 中是否仍启用 shouldAutorotate() 函数。但是,我建议调用以下函数之一作为管理 ViewController 旋转的标准程序的一部分。 (apple developer webside 中的“处理视图旋转”部分,例如 preferredInterfaceOrientationForPresentation

相关问题