iosswiftxcodexcode-storyboardxcode13

Xcode 13: Locking View Orientation


I am trying to create a layout with two views- denoted by the purple and red boxes in the attached image. I want the position of the views to basically lock, such that when the phone rotates the two views remain in the same spot.

I can't figure out how to do this in swift storyboard. I've seen some similar posts, but they don't seem to apply to Xcode 13.

Desired result:

Desired Result


Solution

  • Step 1: Create Portrait view the usual way, using proper constraints. For example I had this:

    enter image description here

    Step 2: Click Orientation button at the bottom of the view to flip the view to landscape

    enter image description here

    Step 3: Add a variation for all constraints that require to be different on horizontal view. For example in my example "SmallerView.leading = Safe Area.leading" is still fine (needs no variation), but "SmallerView.trailing = Safe Area.trailing" makes no sense in horizontal view, I need "SmallerView.trailing = LargerView.leading" instead. So I need to add variation to both, "SmallerView.trailing = Safe Area.trailing", and "LargerView.leading".

    To do that, I simply open Attributes Inspector for a constraint I need to vary, find the word Installed, and click on Add Variation (+ button) on the left of it:

    enter image description here

    The variation I want to add is for Compact Height, and either Regular or Any Width (depends on which devices you are planning to support). Click Add Constraint.

    enter image description here

    Now I see this:

    enter image description here

    But I want to use this constraint only in Portrait view, so I need to uncheck hC:

    enter image description here

    Do the same for all other constraints that won't work for Horizontal view.

    Step 4: Now I need to add constraints specific to horizontal view. To do that, switch to horizontal view (the Orientation button at the toolbar at the bottom)

    You will now see your constraints with some of them disabled:

    enter image description here

    And now you can add missing constraints. For example in my case I added 3 new constraints:

    enter image description here

    Step 5: Switch to Portrait, and now disable those additional constraints from step 4 in portrait mode. This time you uncheck Installed that has no hC prefix:

    enter image description here

    That's it. Check Class Sizes to know when you should use Regular or Compact exactly.