Auto Layout

2 minutes, 42 seconds

“Auto Layout dynamically calculates the size and position of all the views in your view hierarchy, based on constraints placed on those views.”

Instead of specifying an exact location for each component, you can use constraints to place it in relation to other components in your storyboard. Each element under Auto Layout has four defined constraints: x-position, y-position, height and width.

These constraints don’t have to be fixed values — and many times, they’re not! Instead of defining an exact value for the x-position, you can instruct a view to center itself horizontally in its super view. The actual x-position depends on the width of the view on the user’s screen.


Here is the attributes for AutoLayout inside a view.


Constrain Attributes:
– Left or leading
– Right or trailing
– Top
– Bottom
– Baseline
– Center X
– Center Y

Size Attributes:
– Width
– Height


Here are 3 examples for real app situation that using Auto Layout.


1. Pin Constrains with Fixed Size


See the View 1, it has top, leading, trailing constrains, and it also has a fixed height.

For the View 2, it has relationship with the View 1, with vertical spacing. It also has constrains to superview for leading and trailing. View 2 is depending on View 1 to define its position in Y-axis. If View 1 deleted, View 2 will lost definition for Y-axis positioning.

2. Alignment with Fixed Size


View is centered for X and Y. It has fixed width and height.

It will be centered no mater how the superview changing.

3. Equal Width / Height With Scale


In this case we have 2 Views; Top View and Bottom View, arranged vertically.

Both Views has equal width with superview.

Equal height with superview, at first. Then change the multiplier to 0.5 which means 50% from the height length.

We also have pin for both Views, Top View with top pin, Bottom View with bottom pin.

Lastly, we have to center both Views with X-axis center.

Further Reading:

Apple AutoLayout PG