【问题标题】:Setting device orientation in Swift iOS在 Swift iOS 中设置设备方向
【发布时间】:2014-10-28 09:44:10
【问题描述】:

我正在为 iPhone 开发一个 swift 应用程序。我的应用程序中有一个模态视图,我只想在纵向视图中。

我的问题是,如何以编程方式强制手机不允许旋转?换句话说,我正在寻找不允许模式视图以横向模式显示的代码(打开纵向旋转锁定)。

这仅适用于 1 个模态视图,因此我无法关闭整个应用的旋转,否则我将完全禁用旋转。

我在研究中发现了代码here 但它在目标 C 中,以防万一。谢谢!

【问题讨论】:

标签: swift ios8 rotation


【解决方案1】:

斯威夫特 4:

最简单的答案,就我而言,需要确保一个入门教程视图是纯纵向的:

extension myViewController {
    //manage rotation for this viewcontroller
    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
}

Eezy-peezy。

【讨论】:

    【解决方案2】:

    从 ios 10.0 开始,我们需要 set { self.orientations = newValue } 来设置方向,确保在您的项目中启用横向属性。

    private var orientations = UIInterfaceOrientationMask.landscapeLeft
    override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
        get { return self.orientations }
        set { self.orientations = newValue }
    }
    

    【讨论】:

      【解决方案3】:

      斯威夫特 3

      如果视图控制器嵌入在 UINavigationController 或 UITabBarController 中,则方向旋转会更加复杂,导航或标签栏控制器优先并决定自动旋转和支持的方向。

      在 UINavigationController 和 UITabBarController 上使用以下扩展,以便嵌入在这些控制器之一中的视图控制器做出决定:

      UINavigationController 扩展

      extension UINavigationController {
      
      override open var shouldAutorotate: Bool {
          get {
              if let visibleVC = visibleViewController {
                  return visibleVC.shouldAutorotate
              }
              return super.shouldAutorotate
          }
      }
      
      override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
          get {
              if let visibleVC = visibleViewController {
                  return visibleVC.preferredInterfaceOrientationForPresentation
              }
              return super.preferredInterfaceOrientationForPresentation
          }
      }
      
      override open var supportedInterfaceOrientations: UIInterfaceOrientationMask{
          get {
              if let visibleVC = visibleViewController {
                  return visibleVC.supportedInterfaceOrientations
              }
              return super.supportedInterfaceOrientations
          }
       }}
      

      UITabBarController 扩展

      extension UITabBarController {
      
      override open var shouldAutorotate: Bool {
          get {
              if let selectedVC = selectedViewController{
                  return selectedVC.shouldAutorotate
              }
              return super.shouldAutorotate
          }
      }
      
      override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
          get {
              if let selectedVC = selectedViewController{
                  return selectedVC.preferredInterfaceOrientationForPresentation
              }
              return super.preferredInterfaceOrientationForPresentation
          }
      }
      
      override open var supportedInterfaceOrientations: UIInterfaceOrientationMask{
          get {
              if let selectedVC = selectedViewController{
                  return selectedVC.supportedInterfaceOrientations
              }
              return super.supportedInterfaceOrientations
          }
      }}
      

      现在您可以在您想要锁定的视图控制器中覆盖supportedInterfaceOrientations、shouldAutoRotate 和preferredInterfaceOrientationForPresentation,否则您可以忽略在您想要继承应用plist 中指定的默认方向行为的其他视图控制器中的覆盖。

      锁定到特定方向

      class YourViewController: UIViewController {
      open override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
          get {
              return .portrait
          }
      }}
      

      禁用旋转

          class YourViewController: UIViewController {
      open override var shouldAutorotate: Bool {
          get {
              return false
          }
      }}
      

      更改演示的首选界面方向

      class YourViewController: UIViewController {
      open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
          get {
              return .portrait
          }
      }}
      

      【讨论】:

      • 它不适用于 swift 4,显示“覆盖”只能在类成员上指定”
      【解决方案4】:

      我的微薄贡献(Xcode 8、Swift 3):

      func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
              if let rootViewController = self.topViewControllerWithRootViewController(rootViewController: window?.rootViewController) {
                  if (rootViewController.responds(to: Selector(("canRotate")))) {
                      // Unlock landscape view orientations for this view controller
                      return .allButUpsideDown;
                  }
              }
              return .portrait;        
          }
      
          private func topViewControllerWithRootViewController(rootViewController: UIViewController!) -> UIViewController? {
              if (rootViewController == nil) { return nil }
              if (rootViewController.isKind(of: (UITabBarController).self)) {
                  return topViewControllerWithRootViewController(rootViewController: (rootViewController as! UITabBarController).selectedViewController)
              } else if (rootViewController.isKind(of:(UINavigationController).self)) {
                  return topViewControllerWithRootViewController(rootViewController: (rootViewController as! UINavigationController).visibleViewController)
              } else if (rootViewController.presentedViewController != nil) {
                  return topViewControllerWithRootViewController(rootViewController: rootViewController.presentedViewController)
              }
              return rootViewController
          }
      

      ... 在 AppDelegate 上。 Gandhi Mena 的所有学分:http://www.jairobjunior.com/blog/2016/03/05/how-to-rotate-only-one-view-controller-to-landscape-in-ios-slash-swift/

      【讨论】:

        【解决方案5】:

        适用于 Swift 3、iOS 10

        override open var shouldAutorotate: Bool {
            return false
        }
        
        override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
            return .portrait
        }
        
        override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
            return .portrait
        }
        

        但是,shouldAutorotate 设置存在一个错误,目前在 iOS 9 上不起作用。

        【讨论】:

          【解决方案6】:

          欢迎 LandscapeLeft 和 LandscapeRight (更新 Swift 2.0)

          你有这个信息

          还有 UIController

          override func shouldAutorotate() -> Bool {
              return true
          }
          
          override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
              return [UIInterfaceOrientationMask.LandscapeLeft,UIInterfaceOrientationMask.LandscapeRight]
          }
          

          对于 PortraitUpsideDown 和 Portrait 使用

          override func shouldAutorotate() -> Bool {
              if (UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeLeft ||
                  UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeRight ||
                  UIDevice.currentDevice().orientation == UIDeviceOrientation.Unknown) {
                      return false
              }
              else {
                  return true
              }
          }
          
          override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
              return [UIInterfaceOrientationMask.Portrait ,UIInterfaceOrientationMask.PortraitUpsideDown]
          }
          

          来自法国的消息,圣诞快乐!

          编辑:

          其他解决方案:

          extension UINavigationController {
              public override func shouldAutorotate() -> Bool {
                  if visibleViewController is MyViewController {
                      return true   // rotation
                  } else {
                      return false  // no rotation
                  }
              }
          
              public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
                  return (visibleViewController?.supportedInterfaceOrientations())!
              }
          }
          

          【讨论】:

          • 在信息中很好地找到了 iPad 方向
          • @dark-_-d0g 在最后一个语句中不应该在第一个语句中为真而在第二个语句中为假吗?可能是剪切和粘贴错字...
          • 我认为对于纵向视图和 UIDeviceOrientation.Unknown shouldRotate() 的情况应该返回 true。在我的测试中,如果 iPad 在应用程序启动时处于横向模式,则应用程序将保持此模式。
          【解决方案7】:

          斯威夫特 2.2

              func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
          
              if self.window?.rootViewController?.presentedViewController is SignatureLandscapeViewController {
          
                  let secondController = self.window!.rootViewController!.presentedViewController as! SignatureLandscapeViewController
          
                  if secondController.isPresented {
          
                      return UIInterfaceOrientationMask.LandscapeLeft;
          
                  } else {
          
                      return UIInterfaceOrientationMask.Portrait;
                  }
          
              } else {
          
                  return UIInterfaceOrientationMask.Portrait;
              }
          }
          

          【讨论】:

          • 我必须把这个放在哪里?在 AppDelegate 中?如果我这样做,我会收到以下错误:'UIApplicationInvalidInterfaceOrientation',原因:'支持的方向与应用程序没有共同方向,并且 [MyProject.MainViewController shouldAutorotate] 返回 YES'
          • 把这个函数放到AppDelegate中。并从您的 [MyProject.MainViewController shouldAutorotate] 中删除 taht func 返回 YES'。谢谢
          【解决方案8】:

          Go to your pList and add or remove the following as per your requirement:
          
          "Supported Interface Orientations" - Array
          "Portrait (bottom home button)" - String
          "Portrait (top home button)" - String
          "Supported Interface Orientations (iPad)" - Array
          "Portrait (bottom home button)" - String
          "Portrait (top home button)" - String
          "Landscape (left home button)" - String
          "Landscape (right home button)" - String
          

          注意:此方法允许旋转整个应用程序。

          或

          为项目中的 UIViewControllers 制作 ParentViewController (继承方法)。

          //  UIappViewController.swift
          
          import UIKit
          
          class UIappViewController: UIViewController {
                    super.viewDidLoad()   
              }
          //Making methods to lock Device orientation.
              override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
                  return UIInterfaceOrientationMask.Portrait
              }
              override func shouldAutorotate() -> Bool {
                  return false
              }                                                                                                                                       
              override func didReceiveMemoryWarning() {
                      super.didReceiveMemoryWarning()
                      // Dispose of any resources that can be recreated.
                  }
              }
          

          将每个视图控制器的父控制器关联为 UIappViewController。

          //  LoginViewController.swift
          
          import UIKit
          import Foundation
          
          class LoginViewController: UIappViewController{
          
              override func viewDidLoad()
              {
                  super.viewDidLoad()
          
              }
              override func didReceiveMemoryWarning() {
                  super.didReceiveMemoryWarning()
              }
          

          【讨论】:

            【解决方案9】:

            您可以将这些方法粘贴到每个需要纵向的视图的ViewController中:

            override func shouldAutorotate() -> Bool {
                return false
            }
            
            override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
                return UIInterfaceOrientationMask.Portrait
            }
            

            【讨论】:

            • 如果调用模态视图时设备处于横向模式,则此代码不起作用。在这种情况下,模态视图以横向模式显示,并且不能向外旋转。我该怎么办?不过,感谢您的回答,如果我们能解决这个问题,我会接受。
            • 编辑为将UIInterfaceOrientation 转换为Int。这是一个 UInt 值,当前版本的 Swift 现在需要强制转换。
            • 如果您在导航控制器中有一个 VC,如果您只希望它应用于一个 VC 而不是全部,我不相信这会起作用。
            • 应该使用UIInterfaceOrientationMask 而不是UIInterfaceOrientation
            • 你应该从shouldAutorotate()返回true。
            【解决方案10】:

            如果有人想要答案,我想我已经知道了。试试这个:

            • 转到您的 .plist 文件并检查所有方向。
            • 在要强制定向的视图控制器中,添加以下代码:
            override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
                return UIInterfaceOrientationMask.Portrait.toRaw().hashValue | UIInterfaceOrientationMask.PortraitUpsideDown.toRaw().hashValue
            }
            

            希望对你有帮助!

            编辑:

            要强制旋转,请使用以下代码:

            let value = UIInterfaceOrientation.LandscapeRight.rawValue
            UIDevice.currentDevice().setValue(value, forKey: "orientation")
            

            它适用于 iOS 7 和 8!

            【讨论】:

            • 我不得不用“.rawValue”替换“.toRaw()”。虽然仍然不适合我:/
            • UIDevice.currentDevice().setValue(value, forKey: "orientation") 可能会让您的应用在 App Store 被拒绝。您不能像这样设置设备的方向。
            • 我们在设置设备的方向键时不应该使用 UIDeviceOrientation 枚举而不是 UIInterfaceOrientation 吗?由于枚举没有相同的值,我猜将它们混合起来很危险。
            • 那么正确的方法是什么?当用户点击按钮时,我需要改变屏幕方向。
            • 不起作用;错误:无法分配给属性:“方向”是一个只能获取的属性
            【解决方案11】:

            // 斯威夫特 2

            override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
                let orientation: UIInterfaceOrientationMask =
                [UIInterfaceOrientationMask.Portrait, UIInterfaceOrientationMask.PortraitUpsideDown]
                return orientation
            }
            

            【讨论】:

            • 在经历了许多选项之后,@Leo 的这个选项是唯一对我有用的选项。我正在使用 Xcode 7.3、IOS 9.3 和 Swift 2.2
            【解决方案12】:

            如果您的视图控制器属于导航控制器,上述代码可能无法正常工作。如果是,那么即使它本身有不同的方向规则,它也必须遵守导航控制器的规则。更好的方法是让视图控制器自己决定,导航控制器将使用最顶层视图控制器的决定。

            我们可以通过 UINavigationController 上的这个通用扩展支持锁定到当前方向和自动旋转以锁定特定方向:-:

            extension UINavigationController {
                        public override func shouldAutorotate() -> Bool {
                            return visibleViewController.shouldAutorotate()
                        }
            
                    public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
                        return (visibleViewController?.supportedInterfaceOrientations())!
                    }
                }
            

            现在在你的视图控制器中我们可以

            class ViewController: UIViewController {
                // MARK: Autoroate configuration
            
                override func shouldAutorotate() -> Bool {
                    if (UIDevice.currentDevice().orientation == UIDeviceOrientation.Portrait ||
                        UIDevice.currentDevice().orientation == UIDeviceOrientation.PortraitUpsideDown ||
                        UIDevice.currentDevice().orientation == UIDeviceOrientation.Unknown) {
                            return true
                    }
                    else {
                        return false
                    }
                }
            
                override func supportedInterfaceOrientations() -> Int {
                    return Int(UIInterfaceOrientationMask.Portrait.rawValue) | Int(UIInterfaceOrientationMask.PortraitUpsideDown.rawValue)
                }
            }
            

            希望对您有所帮助。 谢谢

            【讨论】:

            • 我相信你是对的!但是......我制作了一个navigationController swift文件并放入扩展名。我把 print's 放进去,发现它只是第一次被调用。屏幕之间的正常移动不会调用扩展中的函数。 .
            • 嗨@Vivek,我使用了你的代码,它工作正常。但我不明白我的一些视图控制器正在旋转,有些很好。你有什么想法吗??
            【解决方案13】:

            @Vivek Parihar 解决方案的两个建议:

            1. 如果我们要展示任何 viewController,我们应该在 navigationController 扩展中检查“visibleViewController”的 nil

              extension UINavigationController {
              public override func shouldAutorotate() -> Bool {
                  var shouldAutorotate = false
                  if visibleViewController != nil {
                      shouldAutorotate = visibleViewController.shouldAutorotate()
                  }
                  return shouldAutorotate
              }
              
              public override func supportedInterfaceOrientations() -> Int {
                  return visibleViewController.supportedInterfaceOrientations()
              }
              }
              
            2. 如果我们使用任何操作表来呈现并且用户将上下旋转,您的操作表将从屏幕的顶部边缘打开:P,为了解决这个问题,我们应该只拍摄肖像

              override func shouldAutorotate() -> Bool {
              if (UIDevice.currentDevice().orientation == UIDeviceOrientation.Portrait ||
                  UIDevice.currentDevice().orientation == UIDeviceOrientation.Unknown) {
                      return true
              }
              else {
                  return false
              }
              

              }

              override func supportedInterfaceOrientations() -> Int {
                  return Int(UIInterfaceOrientationMask.Portrait.rawValue)
              }
              

            【讨论】:

              【解决方案14】:

              更多类似 Swift 的版本:

              override func shouldAutorotate() -> Bool {
                  switch UIDevice.currentDevice().orientation {
                  case .Portrait, .PortraitUpsideDown, .Unknown:
                      return true
                  default:
                      return false
                  }
              }
              
              override func supportedInterfaceOrientations() -> Int {
                  return Int(UIInterfaceOrientationMask.Portrait.rawValue) | Int(UIInterfaceOrientationMask.PortraitUpsideDown.rawValue)
              }
              

              UINavigationController 来自 Vivek Parihar

              extension UINavigationController {
                  public override func shouldAutorotate() -> Bool {
                      return visibleViewController.shouldAutorotate()
                  }
              }
              

              【讨论】:

                【解决方案15】:

                这将禁用视图的自动旋转:

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

                更新

                override func shouldAutorotate() -> Bool {
                    if (UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeLeft ||
                        UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeRight ||
                        UIDevice.currentDevice().orientation == UIDeviceOrientation.Unknown) {
                            return false;
                    }
                    else {
                        return true;
                    }
                }
                

                如果应用程序处于横向模式并且您显示必须以纵向模式显示的视图,这将允许应用程序将其方向更改为纵向(当然当设备将旋转到这样的方向时)。

                【讨论】:

                  【解决方案16】:

                  在 info.plist 文件中,在“支持的界面方向”中更改您想要的方向。

                  以swift方式支持文件->info.plist->支持界面方向。

                  【讨论】:

                    【解决方案17】:

                    我整个上午都在苦苦挣扎,只能正确支持左右横向。我发现了一些非常烦人的事情;尽管“常规”选项卡允许您取消选择设备方向的“纵向”,但您必须编辑 plist 本身以禁用纵向和 PortraitUpsideDown 接口方向 - 这是 plist 中的最后一个键:“支持的接口方向”。

                    另一件事是,您似乎必须使用枚举的“掩码”版本(例如,UIInterfaceOrientationMask.LandscapeLeft),而不仅仅是方向。让它为我工作的代码(在我的主视图控制器中):

                    override func shouldAutorotate() -> Bool {
                        return true
                    }
                    
                    override func supportedInterfaceOrientations() -> Int {
                        return Int(UIInterfaceOrientationMask.LandscapeLeft.rawValue) | Int(UIInterfaceOrientationMask.LandscapeRight.rawValue)
                    }
                    

                    将 plist 更改和代码结合起来是我能够使其正常工作的唯一方法。

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2017-10-13
                      • 2013-10-10
                      • 1970-01-01
                      • 1970-01-01
                      • 2011-12-19
                      • 2014-11-05
                      相关资源
                      最近更新 更多