Shawjak3
Shawjak3

Reputation: 541

How to change layout based on orientation on ipad?

I was just looking at the clock app on the new ipad air 2 and when changing the orientation it affects the layout. There are 6 clocks in the world clock tab and in portrait there are 2 rows of 3 clocks but in landscape there is 1 row of 6 clocks.

I dont see anything based on the size classes in xcode 6 allowing a differentiation of landscape to portrait, is there a different/better way of doing this?

Upvotes: 2

Views: 2186

Answers (2)

trevorj
trevorj

Reputation: 2039

There's a method--willTransitionToTraitCollection:withTransitionCoordinator:--that lets you know when any trait (e.g. horizontal size class, vertical size class, display scale, or user interface idiom) changes.

You can check newCollection.verticalSizeClass to see if it equals .Compact (landscape) or .Regular (portrait) when UIDevice.currentDevice().userInterfaceIdiom != .Pad

So, for example:

override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator)
    if UIDevice.currentDevice().userInterfaceIdiom != .Pad {
        switch newCollection.verticalSizeClass {
        case .Compact:
            goLandscapeWithCoordinator(coordinator)
        case .Regular, .Unspecified:
            hideLandscapeWithCoordinator(coordinator)
        }
    }
}

goLandscapeWithCoordinator(coordinator) could look something like this, for instance:

func goLandscapeWithCoordinator(coordinator: UIViewControllerTransitionCoordinator) {

    let landscapeVC = storyboard!.instantiateViewControllerWithIdentifier("LandscapeViewController") as? LandscapeViewController

    if let controller = landscapeVC {

        controller.view.frame = view.bounds
        controller.view.alpha = 0

        view.addSubview(controller.view)
        addChildViewController(controller)

        coordinator.animateAlongsideTransition({ _ in
            controller.view.alpha = 1
            },
            completion: { _ in
                controller.didMoveToParentViewController(self)
        })

    }
}

Upvotes: 1

Dustin Jia
Dustin Jia

Reputation: 67

If you open storyboard you can find "wAny hAny" on top of the console, which allows you to specify the width and height type (compact, any, regular). If you specified some type then do layout work on storyboard, your layout will only show on the specific situation, which means you can specify different layouts in storyboard for portrait and landscape modes. For example, you can choose "Compact Width | Regular Height" the layout will be shown for all iPhones in portrait mode, and if you choose "Regular Width | Compact Height" the layout will be applied for 5.5 inch iPhones in landscape mode.

Upvotes: 1

Related Questions