SpaceDog SpaceDog - 18 days ago 7
iOS Question

What constraints I should apply to this image view?

I come from design. Using Auto layout to me is like trying to understand Klingon without any previous knowledge of that language. Auto layout defies all logic of good understanding.

I have this situation:

enter image description here

An image view that is 400x400 pixels to be shown portrait and landscape. This image has to be shown with the aspect ratio of 1:1 and adjust itself to be smaller when the device is landscape.

The "image editing" logic says I have to apply the following constraints:

  1. 1:1 aspect ratio

  2. leading/trailing of 10 points.

  3. center Y to view

This works on portrait but when I rotate the device to landscape, the image will expand to respect the leading/trailing of 10 points and it will be clipped top/bottom.

Then I thought, I can add a top/bottom constraint to the view
>= 10 pt
... nope. The image is stretched horizontally and does not respect the aspect ratio of 1:1.

Then I changed the leading/trailing to
and now the image has this:

  1. 1:1 aspect ratio

  2. leading/trailing of >=10 points.

  3. top/bottom of >=10 points.

This is working but Xcode is complaining that the image view needs constraints for Y position or height!

For me, Y is defined perfectly based on the leading/trailing/top/bottom constraints and I cannot define height because each device this runs will have one height.

For God's sake. How to solve that?


Couple ways to go about this, but probably the easiest is:

Set Leading, Trailing, Top and Bottom constraints all to 10

Set the ImageView's Content Mode to Aspect Fit