UIDevice当前设备的“方向”始终为null。

8
根据标题,调用[[UIDevice currentDevice] BeginGeneratingDeviceOrientationNotifications]没有任何效果。
DidRotateToInterfaceOrientation等事件正常工作,但我需要能够随意轮询设备方向。
我该如何修复/实现这个?
长话短说:我有一个选项卡应用程序,每个选项卡都有一个导航控制器。选项卡一的根视图是一个图表,当方向变为横向时,它会全屏显示;然而,每当视图出现时都需要检查此项,因为方向更改可能发生在其他地方,所以我希望在此视图出现时轮询方向状态。
5个回答

9

UIDevice对方向的概念似乎只在实际设备上可用。无论是否启用了文档建议的通知,模拟器似乎总是返回0。非常不方便,但就是这样。

我发现这在实际设备上运行良好:

    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    NSLog(@"orientation: %d", [[UIDevice currentDevice] orientation]);
    [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];

1
是的,我浪费了2个小时来弄清楚问题出在哪里,但实际上只是模拟器的问题。在设备上一切都正常工作。 - samvermette
5
如果用户从Springboard锁定设备方向,[[UIDevice currentDevice] orientation]将无法使用。此时,设备的方向始终为上一次的值,并且没有更改的通知。 - Jeff
5
UIDeviceOrientation interfaceOrientation = [UIApplication sharedApplication].statusBarOrientation; 这个替代方案对我很有效。 - iMeMyself

2

看起来似乎是一个愚蠢的问题,但它不是

beginGeneratingDeviceOrientationNotifications

(小写b)...


2

如果您在- (void)viewDidLoad中检查[[UIDevice currentDevice] orientation],您将始终得到nil。

请在* - (void) viewDidAppear:(BOOL)*动画方法中检查它,然后您


1
“...你总是会得到nil”。这个有记录吗? - Ben Collins

1

这是根据iMeMyself在上面的评论所说的 - 这节省了我很多时间,我认为这是正确的答案,所以我想在这里强调一下:

UIDeviceOrientation interfaceOrientation = [UIApplication sharedApplication].statusBarOrientation;

if (UIInterfaceOrientationIsLandscape(interfaceOrientation))
{
   //do stuff here
}
else if (UIInterfaceOrientationIsPortrait(interfaceOrientation))
{
//or do stuff here
}

这对我有用,但不应该是 UIInterfaceOrientation interfaceOrientation=[.... 吗? - Jimmery

0

[[UIDevice currentDevice] orientation] 不会给你当前的方向状态吗?您可以在想要轮询的视图控制器的viewWillAppear方法中检查此内容。

编辑:除此之外,还有其他获取当前方向的方法,例如使用UIApplication中的statusBarOrientation属性或UIViewcontroller中的interfaceOrientation属性。


看起来你没有仔细阅读问题。他说尽管调用了beginGeneratingOrientationNotifications方法,但该方法仍返回NULL。 - Jasarien

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