Search code examples
iosuikitorientationuistackview

iOS: how to have a different layout depending on app orientation?


I use UIKit and would like to have a completely different interface depending on the app orientation. I actually have 4 buttons on a view, here is how I want to display them:

enter image description here

I know that I can play around with trait variations, setting two different constraints and installing one for regular height and the other for compact height, but I don't know how to do such a different layout in that case.

Thank you for your help


Solution

  • OK - step-by-step...

    Add 4 buttons to your view controller:

    enter image description here

    Embed Buttons 1 & 2 in a stack view, and embed Buttons 3 & 4 in a stack view:

    enter image description here

    Give each stack view these settings:

    enter image description here

    Now, embed the two stack views in another "outer" stack view:

    enter image description here

    Same stack view settings:

    enter image description here

    and constrain this "outer" stack view Leading / Trailing / Bottom at 40-pts.

    Next, select the Buttons 1 & 2 stack view, and in the Attributes Inspector pane click the + to the left of Axis and change Width to Any and Height to Compact:

    enter image description here

    Click Add Variation and it will look like this:

    enter image description here

    Change the hC: Vertical to hC: Horizontal:

    enter image description here

    Do the same thing with the 3 & 4 stack view.

    Now when you rotate the device, it will look like this:

    enter image description here

    Adjust the constraints and your stack view Spacing from 40 to your desired values.

    No code needed - everything is handled by auto-layout!