Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Auto Layout to stack views vertically in portrait mode and horizontally in landscape mode?

I've got two views 'View A' and 'View B'. I'd like to display them side by side in landscape mode but one over the other in portrait mode. How can I achieve this using Auto Layout?Views stacked side by side in Landscape

Views stacked top to bottom in Portrait

like image 504
user1890689 Avatar asked Sep 28 '14 22:09

user1890689


1 Answers

With the new UIStackView (introduced in iOS 9.0) it is now easily possible. Just add a UIStackView in the storyboard with your two views and define the desired proportion.

Then in the ViewController you can adapt the alignment of the axis directly on orientation change:

override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
    switch UIDevice.currentDevice().orientation {
    case .Portrait:
        self.stackview.axis = .Vertical
    case .PortraitUpsideDown:
        self.stackview.axis = .Vertical
    case .LandscapeLeft:
        self.stackview.axis = .Horizontal
    case .LandscapeRight:
        self.stackview.axis = .Horizontal
    default:
        self.stackview.axis = .Vertical
    }
}
like image 190
Prine Avatar answered Oct 03 '22 07:10

Prine