Search code examples
iosautolayoutinterface-builder

Set view as percentage of width in portrait and percentage of height in landscape, in interface builder using autolayout


I am creating a launch screen that has a centered image. I want the image to be 0.7 of the width in portrait orientation and 0.7 of the height in landscape orientation, so the image is the same size in both orientations, but relative to device size. It would be smaller on iPhones and larger on iPads, while supporting both orientations on iPad.

I can do one of those constraints but not both. For example, if I make it 0.7 of the width in portrait then it looks good in portrait but then oversized in landscape, and vice versa.

How do I create such autolayout purely in interface builder? (I'm assuming launch screens must only use IB.)


Solution

  • The trick is to add two sets of proportional width and height constraints...

    First:

    • centerX
    • centerY
    • 1:1 aspect ratio

    Then:

    • width <= 0.7 @1000
    • width = 0.7 @750
    • height <= 0.7 @1000
    • height = 0.7 @750

    So our constraints are saying:

    • try to make width and height each at 70% -- Priority: 750 (High, but not Required)
    • but keep the image view at 1:1 ratio -- Priority: 1000 (Required)
    • and neither width nor height can be greater than 70% -- Priority: 1000 (Required)

    Here's how it looks in the Document Outline pane:

    enter image description here

    and here's what we get for iPad 9.7":

    enter image description here

    enter image description here

    and iPhone 11:

    enter image description here

    enter image description here