首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UIInterfaceOrientation窃听器?

UIInterfaceOrientation窃听器?
EN

Stack Overflow用户
提问于 2010-10-29 11:05:54
回答 3查看 2.4K关注 0票数 1

在我的iPhone应用程序中,我需要检测当前的方向,我必须确定我是在肖像还是风景中。我使用以下代码:

代码语言:javascript
复制
UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
     NSLog(@"portrait");
     ...
} else {
     NSLog(@"landscape");
     ...
}

当我的iPhone在我手里的时候,一切都很好。但是,当我把它放在桌面上运行应用程序时,内容会以纵向模式显示在屏幕上,我的代码转到else,NSLog打印景观

我的测试不完整吗?如何防止这种情况发生?

编辑:测试是在我的控制器viewDidLoad方法和应用程序句柄旋转中执行的。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-10-29 11:22:03

UIDevice.orientationUIDeviceOrientation类型的,它是UIInterfaceOrientation的超集。您可能会得到值UIDeviceOrientationFaceUp

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

代码语言:javascript
复制
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);
}

如果你错过了什么,你就会知道。

票数 3
EN

Stack Overflow用户

发布于 2010-10-29 11:25:13

UIDevice.orientation可以返回设备是平的或倒过来的(而不是倒置的肖像,倒挂就像躺在脸上一样)。相反,在根视图控制器上调用UIViewController.interfaceOrientation。

票数 2
EN

Stack Overflow用户

发布于 2012-05-15 22:37:59

我建议使用UIDeviceOrientationIsValidInterfaceOrientation(orientation)

它会告诉你它是否是一个有效的方向(有效的是风景或肖像,而不是FaceUp/FaceDown/未知)。然后你就可以把它当作它的肖像,如果它是未知的。

我就是这样做的:

代码语言:javascript
复制
if (UIDeviceOrientationIsValidInterfaceOrientation(interfaceOrientation) && UIInterfaceOrientationIsLandscape(interfaceOrientation)) {
    // handle landscape
} else {
    // handle portrait
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4051204

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档