Home > OS >  Set view as percentage of width in portrait and percentage of height in landscape, in interface buil
Set view as percentage of width in portrait and percentage of height in landscape, in interface buil

Time:02-12

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.)

CodePudding user response:

You need to make constraints in respective of the view. For that, you need to follow the steps mentioned below :

  1. Select your imageView.
  2. Hold the control key and move your cursor to the main view.
  3. Now click Equal widths constraint and give it the desired multiplier.
  4. Repeat the above steps for the Equal Height constraint.
  5. You are ready to go.

CodePudding user response:

To make this work requires adding the equal widths constraints (per @Saumya Gautam's answer - welcome to SO!) but requires a little more tweaking to give the results.

  1. Create equal width constraints to desired percentage (image to super view).
  2. Update constraints: set one of them to "less than or equal" relation and set the other at a priority less than the first, e.g. 900.
  3. Create aspect ratio (1:1) constraint on image.

Constraints:

Constraints

Result, in portrait:

Portrait

In landscape:

Lanscape

CodePudding user response:

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

  • Related