获取当前界面方向的不同方法?

68

我知道有三种方法可以获取当前界面方向:

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

它们之间有什么区别?

4个回答

115

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

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

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


1
关于界面方向的另一个答案 - https://dev59.com/Y3RB5IYBdhLWcg3wZmhz#3897243 - beryllium
3
设备的方向并不一定是用户界面(UI)的方向。例如,如果您的应用程序仅支持横向方向,并且将设备旋转为纵向方向,则设备方向将显示为纵向,但UI的方向仍然是横向(并且也将保持横向)。另外,如果设备放在桌子上平放,它不能确定自己的方向,但始终可以确定UI的方向。 - Mecki
仅仅是一个纠正,当设备放在平面桌子上时,并不是“意外的值(Unexpected value)”。UIDeviceOrientation 在 UIDevice.h 中声明了总共 7 个值,其中包括 UIDeviceOrientationUnknown、UIDeviceOrientationFaceUp 和 UIDeviceOrientationFaceDown。你可以记录 deviceOrientation 的值并查看它是否等于 5 或 6,以判断设备是否面朝上或面朝下。 - cirronimbo
8
self.interfaceOrientation 在 iOS 8 中已经被弃用。 - KPM
同时,iOS 通知中心和控制中心会影响 [[UIDevice currentDevice] orientation] 值。例如,您的应用程序仅支持纵向模式。在这种情况下,您将从左侧和右侧获得通知中心面板和控制中心面板(而不是从顶部和底部)。在这种情况下,当您的设备实际处于横向模式时,您将在 [[UIDevice currentDevice] orientation] 中获得纵向值。 - nickolay

26

[[UIApplication sharedApplication] statusBarOrientation] - 它总是等于以下四个值之一:竖屏,左横屏,右横屏和倒立竖屏。

[[UIDevice currentDevice] orientation] - 它也等同于标准的四个值以及未知、正面朝上或正面朝下。

[[UIApplication sharedApplication] statusBarOrientation] - 是更受欢迎的获取界面方向的方法。


此外,[[UIDevice currentDevice] orientation] "...始终返回0,除非通过调用beginGeneratingDeviceOrientationNotifications启用了方向通知。"(文档) - Olie
9
经过12次偏头痛和5次溃疡的折磨,我可以证实[[UIApplication sharedApplication] statusBarOrientation]是一种更可靠且简单的方法来检测和管理屏幕方向的变化。 - Clifton Labrum

3

iOS 13以后

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

UIWindow.windowScene.interfaceOrientation

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

1
所有视图控制器都有这个功能。
   override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
          //fromInterfaceOrientation.isLandscape
   }

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


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

iOS 9中可正常工作 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接