Search code examples
iosswiftdevice-orientation

iOS: Size classes and device orientation at launch


Here is my problem: rotate an iPhone 6 Plus or an iPad to e.g. LandscapeLeft.

Lets say your app has the following code (only for example)

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {

    return UIInterfaceOrientationMask.Portrait 
    // mine does use All, but with this case you'll understand my question
}

How do I detect if the device should use vertical or horizontal layout when

func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)

is called?

print(UIScreen.mainScreen().bounds.width < UIScreen.mainScreen().bounds.height)
// will return false, because we started in landscape but the layout will be forced to be vertical here

print(UIApplication.sharedApplication().statusBarOrientation == .LandscapeLeft)
// will return true, because we started in landscape but the layout will be forced to be vertical here

The main problem appears on the iPad, because both size classes are regular.

I'm confused and have no idea how to solve this issue.


Solution

  • Don't think of your layouts as vertical and horizontal. Just let the app rotate, and respond to the size class or the size change.

    On the iPad, try to avoid having two layouts. Just use autolayout to rejigger the proportions automatically. But if you must respond to rotation on the iPad, then respond to viewWillTransitionToSize (because the trait collection won't change).