iOS允许不同的屏幕方向,无需自动旋转

时间:2018-01-31 08:02:40

标签: ios objective-c iphone swift

即使用户旋转手机,我也希望保持纵向方向。同时,我想用按钮改变方向。 如果我只将肖像作为支持的方向放在plist中然后旋转,应用程序会给我错误。如果我将所有支持的方向(shouldAutorotate方法)设置为NO,则应用程序崩溃。 所以,基本上我可以看到,如果我让应用程序进行自动旋转,我只能支持多个方向。

我可以达到我的需要吗?

2 个答案:

答案 0 :(得分:1)

shouldAutorotate

这是一个只获取属性。

你能做的是:

override var shouldAutorotate: Bool {
    return false
}

也许这对你来说也很有趣:how to dissable and enable auto rotate on swift?

答案 1 :(得分:-1)

可能以下代码行将适合您。以编程方式设置方向。

  1. 在Appdelegate类中编写以下代码:

    var orientationLock = UIInterfaceOrientationMask.all

    func application(_ application:UIApplication,supportedInterfaceOrientationsFor window:UIWindow?) - > UIInterfaceOrientationMask {         返回self.orientationLock }

  2. 2.制作自定义助手类如下:

    struct AppUtility {
    
        static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
    
            if let delegate = UIApplication.shared.delegate as? AppDelegate {
                delegate.orientationLock = orientation
            }
        }
    
        /// OPTIONAL Added method to adjust lock and rotate to the desired orientation
        static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
    
            self.lockOrientation(orientation)
    
            UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
        }
    
    }
    
    1. 然后在你想要的viewcontroller中使用它,如:

      覆盖func viewDidAppear(_ animated:Bool){     super.viewDidAppear(动画)

      AppUtility.lockOrientation(.portrait)
      // Or to rotate and lock
      // AppUtility.lockOrientation(.portrait, andRotateTo: .portrait)
      

      }

      覆盖func viewWillDisappear(_ animated:Bool){     super.viewWillDisappear(动画)

      // Don't forget to reset when view is being removed
      AppUtility.lockOrientation(.all)
      

      }

    2. 注意:请记住,从目标设置中选中“需要全屏”选项。