UIDevice.orientation
可能的值包括 UIDeviceOrientationFaceUp
和 UIDeviceOrientationFaceDown
。虽然了解设备是否平放可能有用,但这并不能告诉我们它是横向还是纵向显示界面。在设备返回模糊信息的情况下,是否有一种方法可以找到GUI的当前方向?我想我可以跟踪方向更改事件来记住最后一个纵向/横向方向,或者检查主UIView的边界高度和宽度,但这似乎有些笨拙。是否有设备或UIView上的属性我错过了?UIDevice.orientation
可能的值包括 UIDeviceOrientationFaceUp
和 UIDeviceOrientationFaceDown
。虽然了解设备是否平放可能有用,但这并不能告诉我们它是横向还是纵向显示界面。在设备返回模糊信息的情况下,是否有一种方法可以找到GUI的当前方向?我想我可以跟踪方向更改事件来记住最后一个纵向/横向方向,或者检查主UIView的边界高度和宽度,但这似乎有些笨拙。是否有设备或UIView上的属性我错过了?您可以通过以下3种方式获取方向:
UIInterfaceOrientation orientation = self.interfaceOrientation;
返回UIInterfaceOrientation,即界面的当前方向。这是UIViewController的一个属性,在只有UIViewController类中才能访问到该属性。
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
返回UIInterfaceOrientation,即应用程序状态栏的当前方向。在应用程序的任何地方都可以访问该属性。我的经验表明,这是检索实际界面方向最有效的方法。
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
返回UIDeviceOrientation,即设备方向。在应用程序的任何地方都可以访问该属性。但请注意,UIDeviceOrientation并不总是UIInterfaceOrientation。例如,当设备放在平坦的桌子上时,您可能会收到意外的值。
在视图控制器中,您可以简单地使用以下代码:
UIInterfaceOrientation interfaceOrientation = self.interfaceOrientation;
UIInterfaceOrientation是一个枚举类型:
typedef enum {
UIInterfaceOrientationPortrait = UIDeviceOrientationPortrait,
UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,
UIInterfaceOrientationLandscapeLeft = UIDeviceOrientationLandscapeLeft,
UIInterfaceOrientationLandscapeRight = UIDeviceOrientationLandscapeRight
} UIInterfaceOrientation;
如果你只关心设备是横屏还是竖屏,那么在视图控制器上有一些不错的便利方法:
UIDeviceOrientationIsLandscape(self.interfaceOrientation)
UIDeviceOrientationIsPortrait(self.interfaceOrientation)
状态栏方向(statusBarOrientation)始终返回界面方向,即使状态栏被隐藏。
您可以在没有视图控制器的情况下使用状态栏方向。它提供的是当前视图方向,而不是设备方向。
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
我曾经遇到过同样的情况,具体是在以下流程中:
此时,我看到的任何方向检查都会返回无效的方向5,因此不能直接确定应该使用横向还是纵向布局。(我正在按每个方向自定义布局定位,因此这是重要信息)
在我的情况下,对视图进行边界宽度检查以确定真实状态,但我很想知道其他人是否有不同的解决方法。
UIInterfaceOrientation orientation = [UIDevice currentDevice].orientation;
NSLog( @" ORIENTATION: %@", UIInterfaceOrientationIsLandscape( orientation ) ? @"LANDSCAPE" : @"PORTRAIT");