在我的iPhone应用程序中,我需要检测当前的方向,我必须确定我是在肖像还是风景中。我使用以下代码:
UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
NSLog(@"portrait");
...
} else {
NSLog(@"landscape");
...
}当我的iPhone在我手里的时候,一切都很好。但是,当我把它放在桌面上运行应用程序时,内容会以纵向模式显示在屏幕上,我的代码转到else,NSLog打印景观。
我的测试不完整吗?如何防止这种情况发生?
编辑:测试是在我的控制器viewDidLoad方法和应用程序句柄旋转中执行的。
发布于 2010-10-29 11:22:03
UIDevice.orientation是UIDeviceOrientation类型的,它是UIInterfaceOrientation的超集。您可能会得到值UIDeviceOrientationFaceUp。
这说明,是的,你的测试是不完整的。你应该写这样的东西:
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);
}如果你错过了什么,你就会知道。
发布于 2010-10-29 11:25:13
UIDevice.orientation可以返回设备是平的或倒过来的(而不是倒置的肖像,倒挂就像躺在脸上一样)。相反,在根视图控制器上调用UIViewController.interfaceOrientation。
发布于 2012-05-15 22:37:59
我建议使用UIDeviceOrientationIsValidInterfaceOrientation(orientation)
它会告诉你它是否是一个有效的方向(有效的是风景或肖像,而不是FaceUp/FaceDown/未知)。然后你就可以把它当作它的肖像,如果它是未知的。
我就是这样做的:
if (UIDeviceOrientationIsValidInterfaceOrientation(interfaceOrientation) && UIInterfaceOrientationIsLandscape(interfaceOrientation)) {
// handle landscape
} else {
// handle portrait
}https://stackoverflow.com/questions/4051204
复制相似问题