如何在viewDidLoad之前检测设备方向?

4
我需要在控制器中的viewDidLoad方法运行之前检测设备方向。我尝试了其他问题中提出的所有解决方案,但是我无法解决问题。

在xCode 5和iOS 7中,使用SotryBoard的最佳方式是什么?

提前致谢!

编辑:实际上我正在使用

- (void)viewDidLoad {

    [super viewDidLoad];

    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

        switch ([[UIDevice currentDevice] orientation]) {
            case (UIDeviceOrientationPortrait):
                // landscape layout
                break;

            default:
                // portrait layout
                break;
        }

但是它不起作用...

解决方案:使用

- (void)viewDidLoad {

    [super viewDidLoad];

    if([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait || [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown) {
        // Portrait
    }

    if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeLeft || [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeRight){
        // Landscape
    }
}

1
不要混淆 UIDeviceOrientation 和 UIInterfaceOrientation。 - jbat100
你不应该在 viewDidLoad 中进行布局。在这里,你可以设置数据模型和初始化视图,但是所有的布局都应该在 viewWillLayoutSubviews 中完成,因为 self.view.frame 将准确地表示当前的框架,考虑到旋转。 - Aaron Brager
它也适用于storyBoard吗? - Matte.Car
2个回答

3
你需要的是 [[UIDevice currentDevice] orientation] 吗?这个与设备方向相关。

2
这个可能需要调用 [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications] 才能正常工作。 - KIDdAe

2

尝试检查状态栏的方向:

UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];

此外,在viewDidLoad方法之前还有一些其他的视图控制器方法被触发,可以看一下awakeFromNib和initWithCoder方法。

如果状态栏被隐藏,这段代码将无法工作。如果您有其他建议,请分享。谢谢! - Chirag Dj

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