在 Init 函数中检测设备方向

Detect device orientation in Init function

我正在使用这些代码行检测设备方向:

UIDevice.currentDevice().orientation.isPortrait.boolValue
UIDevice.currentDevice().orientation.isLandscape.boolValue

我检测到它是否是 iPad,代码如下:

userInterfaceIdiom == .Pad

我在 commonInit() 函数中使用了此代码,该函数在 Init() 函数中调用。当我在 iPad 上执行我的代码时,前两行 return 都是 false 这是不正确的,其中一个应该是 true。第三行工作正常。

如果我在其他函数中使用该代码,例如 supportedInterfaceOrientations(),它可以正常工作。您知道可能是什么问题吗?

您可能忽略了此文档:

You also use the UIDevice instance to detect changes in the device’s characteristics, such as physical orientation. You get the current orientation using the orientation property or receive change notifications by registering for the UIDeviceOrientationDidChangeNotification notification. Before using either of these techniques to get orientation data, you must enable data delivery using the beginGeneratingDeviceOrientationNotifications method. When you no longer need to track the device orientation, call the endGeneratingDeviceOrientationNotifications method to disable the delivery of notifications.

此外,这是一个 3-D 方向。你可能不想要那个。 orientation 属性 的 实际 值是多少?参见:

enum UIDeviceOrientation : Int {
    case Unknown
    case Portrait
    case PortraitUpsideDown
    case LandscapeLeft
    case LandscapeRight
    case FaceUp
    case FaceDown }

可能你真正想要的在这里:

Sometimes TraitCollections doesn't fill all your design needs. For those cases, Apple recommends to compare view's bounds :

if view.bounds.size.width > view.bounds.size.height { // ... }