UIDavigationController推送后[UIDevice currentDevice] .orientation == UIDeviceOrientationUnknown

use*_*226 7 iphone uinavigationcontroller uiinterfaceorientation uideviceorientation

这是一个比任何事情更多的观察,因为我似乎找到了一个解决方法......

当它在一个已被推送到UINavigationController堆栈的控制器中时,下面的代码无法工作.在这种情况下[UIDevice currentDevice].orientation一直回归UIDeviceOrientationUnknown.

-(void)layoutAccordingToOrientation {
    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
    NSLog(@"layoutAccordingToOrientation/orientation==%i", orientation);
    if (UIInterfaceOrientationIsLandscape(orientation)) {
        :
        _detailToolbar.frame = CGRectMake(0, 660, 1024, 44);
    } else {
        :
        _detailToolbar.frame = CGRectMake(0, 916, 768, 44);
    }
}

-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [self layoutAccordingToOrientation];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}
Run Code Online (Sandbox Code Playgroud)

以下调用取得:

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
Run Code Online (Sandbox Code Playgroud)

要解决这个UIDeviceOrientationUnknown问题,我现在使用以下代码:

UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (UIInterfaceOrientationIsLandscape(orientation)) {
    etc.
} else {
    etc.
}
Run Code Online (Sandbox Code Playgroud)

......每次都有效.

尽管如此,我仍然不明白为什么第一个变体在推送视图控制器的上下文中不起作用.想法有人吗?这只是一个错误吗?

小智 4

我可以在这里想到一些事情,但我不确定它们是你要找的......

首先,当应用程序启动时,通常出于性能原因会返回设备方向UIDeviceOrientationUnknown。您可以尝试的一件事是在 .nib 或 Storyboard 中布局子视图,并使用正确的自动调整大小选项,然后让 iOS 完成它的工作。

其次,如果您像我一样,也许您正在计算机旁边、放在桌子上的设备上进行测试。好吧,在这种情况下,你就不会得到这个UIDeviceOrientationUnknown东西。您实际上应该测试UIDeviceOrientationIsValidInterfaceOrientation([[UIDevice currentDevice] orientation]). 例如,如果设备仰卧,它会对该语句返回“是”。这也意味着当您使用 时UIInterfaceOrientationIsLandscape(orientation),您会因错误的原因而获得正确的结果。返回UIInterfaceOrientationIsLandscapefalse 不是因为设备的方向是UIDeviceOrientationPortrait,而是因为它无效。

不太确定这是否有帮助,但我花了一段时间才弄清楚这一点,我认为分享此信息会很好!:)