Search code examples
iosxcodeautolayout

Image view autolayout to pin 60pt from horizontal edges, but auto scale height?


I'm trying to figure out an approach to the following:

I have a square image, I want to align it horizontally and vertically in the centre of the screen and constrain it in a way where its left and right edges are 60pt from screen edges.

I got thus far, but am now getting an error from XCode about top and bottom image constraints. How can I make it so image keeps its square ratio and auto resizes based on screen size?

Example, images width became 294pt in screenshot below, yet height remained unchanged, where as it should change to 294 pt as well.

enter image description here


Solution

  • You need to add 3 more constraints.

    1. Vertically align your view to superview

    2. Horizontally align your view to superview

    3. Set aspect ratio of your view to 1:1 (Important)

    The image showing how to add Aspect ratio

    On the whole you should have 5 constraints. The screenshot is given below.

    Image Having all 5 constraints for the View that you want to maintain 60 padding, equal width & height and vertically & horizontally aligned