【问题标题】:iPad shows at portrait but thinks it's landscapeiPad 以纵向显示,但认为是横向
【发布时间】:2014-06-14 11:49:30
【问题描述】:

我的 Storybuilder 采用纵向布局设计。当我在 iPad 已转为水平状态的情况下启动应用程序时,它能够正确检测到它处于水平位置。但是当我以纵向位置的 iPad 启动应用程序时,它认为它是水平的。但是,每次我旋转它时,代码都能正确检测到正确的方向。

- (void) viewDidLoad
{
    [self updateForOrientation];
}

- (void)updateForOrientation
{
    if (UIInterfaceOrientationIsPortrait([[UIDevice currentDevice] orientation])) // became portrait
    {
        NSLog(@"is portrait");
        //code for changing layout to portrait position
    }

    else //became horiztontal
    {
        NSLog(@"is horizontal");
        //code for changing layout to horizontal position
    }
}

Output: is horizontal (this is the output whether it starts up as portrait or landscape)

【问题讨论】:

    标签: ios ipad rotation orientation landscape-portrait


    【解决方案1】:

    问题是您将根据 UIDeviceOrientation 枚举的设备方向发送到需要 UIInterfaceOrientation 值的函数。

    如果你命令点击UIInterfaceOrientationIsPortrait(),你可以看到它的定义如下。

    #define UIInterfaceOrientationIsPortrait(orientation)  ((orientation) == UIInterfaceOrientationPortrait || (orientation) == UIInterfaceOrientationPortraitUpsideDown)
    

    如果您查看两种方向类型的枚举声明(下面的文档链接),您会发现由于设备方向包含“无”值而导致值不一致。无论如何,将代码更改为使用 UIInterfaceOrientation 应该可以解决这个问题。示例:

    - (void)updateForOrientation
    {
        UIInterfaceOrientation currentOrientation = self.interfaceOrientation;
    
        if (UIInterfaceOrientationIsPortrait(currentOrientation)) {
            NSLog(@"is portrait");
        }else{
            NSLog(@"is horizontal");
        }
    }
    

    https://developer.apple.com/library/ios/documentation/uikit/reference/UIApplication_Class/Reference/Reference.html#//apple_ref/doc/c_ref/UIInterfaceOrientation

    https://developer.apple.com/library/ios/documentation/uikit/reference/UIDevice_Class/Reference/UIDevice.html#//apple_ref/doc/c_ref/UIDeviceOrientation

    【讨论】: