iPhone 6 Plus 的方向不正确?

Incorrect orientations on iPhone 6 Plus?

我希望我的应用在 iPad 上以所有方向运行,在 iPhone 6 Plus 上支持横向和纵向,在其他设备上仅支持纵向。

但它在 iPhone 6/6s Plus 上无法正常工作。旋转很奇怪,视图控制器经常以错误的方向出现。

这是我目前在 AppDelegate.swift:

func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {

    let height = window?.bounds.height

    if height > 736.0 {
        // iPad
        return .All
    } else if height == 736.0 {
        // 5.5" iPhones
        return .AllButUpsideDown
    } else {
        // 4.7", 4", 3.5" iPhones
        return .Portrait
    }

}

正确的做法是什么?

我们可以使用多种方法来设置适当的界面方向。首先,使用硬编码高度很容易出现错误,Apple 强烈反对这种类型的设备检查。相反,我们将使用特征集合。 UITraitCollection 是 API 在 iOS 8 中引入的,它包含有关设备惯用语、显示比例和大小 类 的信息。您可以访问 UIWindowUIViewController 对象上的特征集合。

在我们的示例中,我们将首先使用 userInterfaceIdiom 属性 检查设备是否为 iPad,然后我们将检查 displayScale 是否为 iPhone 6/6s Plus(即 3.0)。

func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {

        if window?.traitCollection.userInterfaceIdiom == .Pad {
            // Check for iPad
            return .All
        } else if window?.traitCollection.displayScale == 3.0 {
            // iPhone 6/6s Plus is currently only iPhone with display scale of 3.0
            return [.Portrait, .Landscape]
        } else {
            // Return Portrait for all other devices
            return .Portrait
        }
    }

如果你想了解更多关于特征集合和大小的信息类我建议阅读官方Apple documentation