ios - iPhone 6 Plus 的方向不正确?

标签 ios iphone swift ipad orientation

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

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

这是我目前在我的 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 是 iOS 8 中引入的 API,它包含有关设备惯用语、显示比例和大小类的信息。您可以访问 UIWindowUIViewController 对象上的特征集合。

在我们的示例中,我们将首先使用 userInterfaceIdiom 属性检查设备是否为 iPad,然后我们将检查 iPhone 6/6s Plus 的 displayScale(这是 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
        }
    }

如果您想了解更多关于 trait collections 和 size classes 我推荐阅读官方 Apple documentation

关于ios - iPhone 6 Plus 的方向不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37623435/

相关文章:

ios - 如何在 iOS 上自动调整照片(即调亮、对比度)?

iphone - 在iPhone上使用自定义阿拉伯字体时出现问题

ios - 为什么github上的某些ios项目仍然使用IBOutlet而不使用Interface builder文件?

ios - Swift 问题中的 NSXMLDelegate

ios - 需要有关 XCode : Thread 1:EXC_BAD_INSTRUCTION (WebView) 的帮助

swift - 如何反转这个动画? swift 3

ios - 如何远程跟踪 iOS 用户位置?

ios - Xcode 8.1 IOS10.1 CoreData删除并没有真正删除

ios - 快速从日期选择器获取日期

iphone - 异步 NSURLConnection 抛出 EXC_BAD_ACCESS