关于iPhone:UIInterfaceOrientation错误?

UIInterfaceOrientation bug?

在我的iPhone应用程序中,我需要检测当前方向,并且必须确定我是纵向还是横向。我使用以下代码:

1
2
3
4
5
6
7
8
UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
     NSLog(@"portrait");
     ...
} else {
     NSLog(@"landscape");
     ...
}

当我拿起iPhone时,一切都很好。
但是,当我将其放在桌子上并运行该应用程序时,内容将以纵向模式显示在屏幕上,并且我的代码转到其他位置,NSLog会打印横向。

我的考试不完整吗?如何预防这种情况?

EDIT:测试在我的控制器viewDidLoad方法中执行,并且我的应用程序处理旋转。


UIDevice.orientation的类型为UIDeviceOrientation,是UIInterfaceOrientation的超集。您可能会得到值UIDeviceOrientationFaceUp

这说明是的,您的测试不完整。您应该这样写:

1
2
3
4
5
6
7
8
9
10
11
UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
     NSLog(@"portrait");
     ...
} else if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
     NSLog(@"landscape");
     ...
} else {
     NSLog(@"WTF? %d", orientation);
     assert(false);
}

然后,如果您错过了某些内容,您会知道。


UIDevice.orientation可以返回该设备是平坦的还是倒置的(不是倒置的肖像,倒置时就像在其面上放置时那样倒置)。而是在根视图控制器上调用UIViewController.interfaceOrientation。


我建议使用UIDeviceOrientationIsValidInterfaceOrientation(orientation)

它将告诉您其方向是否有效(有效为横向或纵向,不是FaceUp / FaceDown / UnKnown)。然后,可以将其视为未知的肖像。

这是我的操作方式:

1
2
3
4
5
if (UIDeviceOrientationIsValidInterfaceOrientation(interfaceOrientation) && UIInterfaceOrientationIsLandscape(interfaceOrientation)) {
    // handle landscape
} else {
    // handle portrait
}