【问题标题】:Different ways of getting current interface orientation?获取当前界面方向的不同方法?
【发布时间】:2011-12-19 14:05:08
【问题描述】:

据我所知,有 3 种方法可以获取当前界面方向:

  • self.interfaceOrientation
  • [[UIApplication sharedApplication] statusBarOrientation]
  • [[UIDevice currentDevice] orientation]

它们之间有什么区别?

【问题讨论】:

    标签: ios orientation


    【解决方案1】:

    [[UIApplication sharedApplication] statusBarOrientation] - 它始终等于以下四个值之一:纵向、横向左侧、横向右侧和纵向倒置。

    [[UIDevice currentDevice] orientation] - 这一个等于标准的四个值,还有:未知、面朝上或面朝下。

    [[UIApplication sharedApplication] statusBarOrientation] - 是获取界面方向的首选方式。

    【讨论】:

    • 此外,[[UIDevice currentDevice] orientation] "... 始终返回 0,除非已通过调用 beginGeneratingDeviceOrientationNotifications 启用方向通知。" (文档)
    • 12 次偏头痛和 5 次溃疡后,我可以确认 [[UIApplication sharedApplication] statusBarOrientation] 是一种更可靠、更简单的检测和管理方向变化的方法。
    【解决方案2】:

    self.interfaceOrientation 返回 UIInterfaceOrientation,界面的当前方向。它是 UIViewController 中的一个属性,你只能在 UIViewController 类中访问它。

    [[UIApplication sharedApplication] statusBarOrientation] 返回 UIInterfaceOrientation,应用程序状态栏的当前方向。您可以在应用程序的任何位置访问该属性。我的经验表明,它是检索真实界面方向的更有效方法。

    [[UIDevice currentDevice] orientation] 返回UIDeviceOrientation,设备方向。您可以在应用程序的任何位置访问该属性。但请注意,UIDeviceOrientation 并不总是 UIInterfaceOrientation。例如,当您的设备放在普通桌子上时,您可能会收到意外的值。

    【讨论】:

    • 关于界面方向的另一个答案 - stackoverflow.com/a/3897243/194544
    • @Pwner 设备的方向不一定是 UI 的方向。例如。如果您的应用仅支持横向并且您将设备设置为纵向,则设备方向会显示为纵向,但 UI 的方向仍然是横向(并且它也将保持横向)。此外,如果设备平放在桌子上,它无法确定它的方向是什么,但它始终知道 UI 的方向。
    • 只是一个更正,当设备放在普通桌子上时,它不是“意外值”。 UIDeviceOrientation 一共有 7 个值,在 UIDevice.h 中声明,其中包括 UIDeviceOrientationUnknown 、 UIDeviceOrientationFaceUp 、 UIDeviceOrientationFaceDown 。您可以记录 deviceOrientation 值并查看它是否等于 5 或​​ 6 用于 faceUp 或 faceDown。
    • self.interfaceOrientation 在 iOS 8 中已弃用。
    • 还有 ios 通知中心和 ios 控制中心对[[UIDevice currentDevice] orientation] 值的影响。例如,您的应用仅支持纵向模式。在这种情况下,您会从左右(而不是从顶部和底部)获得通知中心面板和控制中心面板。在这种情况下,当您的设备真正处于横向时,您将在 [[UIDevice currentDevice] orientation] 中获得纵向值。
    【解决方案3】:

    所有视图控制器都有这个功能

       override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
              //fromInterfaceOrientation.isLandscape
       }
    

    或者您可以使用状态栏方向

       if UIApplication.sharedApplication().statusBarOrientation == UIInterfaceOrientation.Portrait {
            //
       }
    

    适用于 iOS 9 :)

    【讨论】:

      【解决方案4】:

      自 iOS 13 起

      可以使用窗口场景的interfaceOrientation属性

      UIWindow.windowScene.interfaceOrientation

      let interfaceOrientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation ?? UIInterfaceOrientation.unknown
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-07-04
        • 2011-01-31
        • 2016-03-13
        • 2011-01-04
        • 2011-01-09
        • 2011-04-09
        • 1970-01-01
        相关资源
        最近更新 更多