如何以编程方式确定iPhone界面方向?

53
UIDevice.orientation 可能的值包括 UIDeviceOrientationFaceUpUIDeviceOrientationFaceDown。虽然了解设备是否平放可能有用,但这并不能告诉我们它是横向还是纵向显示界面。在设备返回模糊信息的情况下,是否有一种方法可以找到GUI的当前方向?我想我可以跟踪方向更改事件来记住最后一个纵向/横向方向,或者检查主UIView的边界高度和宽度,但这似乎有些笨拙。是否有设备或UIView上的属性我错过了?
6个回答

95

您可以通过以下3种方式获取方向:

  1. UIInterfaceOrientation orientation = self.interfaceOrientation;返回UIInterfaceOrientation,即界面的当前方向。这是UIViewController的一个属性,在只有UIViewController类中才能访问到该属性。

  2. UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];返回UIInterfaceOrientation,即应用程序状态栏的当前方向。在应用程序的任何地方都可以访问该属性。我的经验表明,这是检索实际界面方向最有效的方法

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


2
不是UIInterfaceOrientation,而是UIDeviceOrientation,在他的帖子中micco已经提到了这一点。 - justadreamer
3
没问题。UIDeviceOrientation并不总是等同于UIInterfaceOrientation。 - beryllium
这个问题困扰了我很久,谢谢。 - hanno
我尝试使用UIDeviceOrientation,但当设备放置在桌子上面朝上时遇到了问题。使用UIInterfaceOrientation解决了这个问题 +1...谢谢 - Aditya
2
在阅读这个答案之前,我一直在使用大量的解决方法,因为我的类并不都是UIView...这个方法非常有效!如果可以的话,我会给这个答案一百万个赞...非常感谢!@beryllium - Highrule
显示剩余4条评论

92

在视图控制器中,您可以简单地使用以下代码:

UIInterfaceOrientation interfaceOrientation = self.interfaceOrientation;

UIInterfaceOrientation是一个枚举类型:

typedef enum {
  UIInterfaceOrientationPortrait           = UIDeviceOrientationPortrait,
  UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,
  UIInterfaceOrientationLandscapeLeft      = UIDeviceOrientationLandscapeLeft,
  UIInterfaceOrientationLandscapeRight     = UIDeviceOrientationLandscapeRight
} UIInterfaceOrientation;

如果我需要开发支持所有界面方向的iPhone应用程序,我该怎么做?您是否知道有哪些文档文件或博客教程可以提供帮助,请告诉我。 - Solid Soft
2
Apple表示:“不要使用此属性(UIViewController.interfaceOrientation)来告知布局决策。相反,请使用在UIApplication类参考中描述的statusBarOrientation属性。” - Paul Bruneau
2
自iOS 8起已被弃用 - heyfrank

14

如果你只关心设备是横屏还是竖屏,那么在视图控制器上有一些不错的便利方法:

UIDeviceOrientationIsLandscape(self.interfaceOrientation)
UIDeviceOrientationIsPortrait(self.interfaceOrientation)

11

状态栏方向(statusBarOrientation)始终返回界面方向,即使状态栏被隐藏。

您可以在没有视图控制器的情况下使用状态栏方向。它提供的是当前视图方向,而不是设备方向。

UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];

5

我曾经遇到过同样的情况,具体是在以下流程中:

  • 控制器 1 加载肖像模式。
  • 将另一个控制器推入堆栈。
  • 在第二个控制器中,将设备方向旋转为横向。
  • 将设备放平在桌子上,然后弹回到原始控制器。

此时,我看到的任何方向检查都会返回无效的方向5,因此不能直接确定应该使用横向还是纵向布局。(我正在按每个方向自定义布局定位,因此这是重要信息)

在我的情况下,对视图进行边界宽度检查以确定真实状态,但我很想知道其他人是否有不同的解决方法。


1
我在iPad上使用状态栏方向作为工作参考点。边界检查对我没有起作用。 - Moshe

1
这是一个你可能会觉得有用的代码片段:

UIInterfaceOrientation  orientation = [UIDevice currentDevice].orientation;
NSLog( @" ORIENTATION: %@", UIInterfaceOrientationIsLandscape( orientation ) ? @"LANDSCAPE" : @"PORTRAIT");

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