如何通过编程获取设备的当前方向?

3
我想知道设备的方向,我使用了
 UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation

但是这仅在我改变方向时才有效,否则它不会返回任何内容(TRUE / FALSE)。那么如何获取当前设备方向,即使未更改方向。

提前致谢!

3个回答

6

获取方向

UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];

可能的方向有:

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

我认为只有在改变方向时才能使其正常工作。我想根据方向(初始方向)创建用户界面。 - user831722

4
UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];

警告隐式枚举。

请改用下面的代码:

UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

1
你不应该使用UIDeviceOrientation来配置与界面方向相关的事物。原因是因为UIDeviceOrientation指定了UIDeviceOrientationFaceUp和UIDeviceOrientationFaceDown值,当将它们应用于UI时没有意义。UIInterfaceOrientation才是正确的方式。 - Pawel

0

抱歉如果您已经这样做了,但是您是否研究过 beginGeneratingDeviceOrientationNotifications 方法,该方法可以启用设备的通知生成?

另外,您是在寻找设备方向还是界面方向?如果您只是想要一个简单的纵向或横向方向信息,您应该查看视图控制器的interfaceOrientation。

希望这可以帮助您!


当我们改变方向时,这个通知将被调用?但我希望即使方向没有改变也能获得方向。 - user831722
再次问候Deepak;是的,据我所见,您可以简单地访问interfaceOrientation属性,它将返回UIInterfaceOrientation下定义的可能方向之一的typedef。 - Madhu
谢谢Madhumal,我找到了解决方案。使用状态栏方向,我们可以找出当前的方向。这解决了我的问题。 - user831722

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