Rici
Rici

Reputation: 1044

For what should I use the Aspect Ratio NSLayoutConstraint?

When I first started working with AutoLayout, I couldn't find any example which helps understanding for what stands the Aspect Ratio NSLayoutConstraint.

Does someone have an example of usage? Thanks!

Upvotes: 1

Views: 255

Answers (1)

user7014451
user7014451

Reputation:

I have a demo example of keeping a square view centered in all devices and orientations here.

The constraints are set up in IB, but you could just as easily set them up in code. Most of this was meant to explain how to prioritize margin constraints to let the auto layout engine know what to break and when, but what makes the view square is the aspect ration - it's 1:1. If you want a rectangle, you make it 2:1 (or 1:2 depending).

Once you understand these two pieces (prioritization and aspect ratio), the last piece is the actual margins values - I set them for 10 points, meaning the square will have 10 point margins on the smallest axis. If the device is an iPad Pro 12.9 inch, you get a very large square. If it's an iPhone SE, you get a very small one. No matter what, you get the 10 point margin. Set the margin values up for 50, and the square view is relatively smaller. The important thing is with an aspect ratio of 1:1, it will always be a square.

Upvotes: 2

Related Questions