Senior iOS Developer
Auto Layout dynamically calculates the size and position of all the views in your view hierarchy. It’s an Xcode feature that you must know when it comes to building the user interface for your next iOS project. With the proper use of constraints, you will make your app responsive to any iPhone size that currently exists.
In this tutorial, I will explain the Auto Layout constraints and how to properly apply them. First of all, I want to mention that you can work with constraints both programmatically or from the Interface Builder. In most cases, you should focus on working with the second approach.
I am sure that you have already seen this bar above the console area. This is the place where all the magic happens. On the right side, you will see 3 tabs that are enabled. That’s everything that you might ever need when working with constraints.
I will start with the middle tab because it’s the most important one. From here, we can add constraints that we need for the selected view. Basically, you can add both position and size type of constraints.
If you can see from the above screenshot, there are 4 red lines at the top of the window. Each line represents a side that we want the selected view to follow. The numbers next to each line, represent how much margin space we want to leave between the selected view and the superview or some other child view. It will connect with anything that is on the specified side.
For example, if you want your view to always be in the top left corner, you will need to add leading and top constraints.
Below the position constraints, we can see the size constraints. They define how big the view will be.
From the first tab, you can add alignment constraints to your selected view. In most cases, you will need just the enabled ones. From here, you can center the view. in the superview either horizontally, vertically or both.
For example, select both Horizontally in Container and Vertically in Container in order to center your selected view in the superview.
Auto Layout provides us with a help section that can resolve our constraint issues fast. There are two types, (1) resolve issues on the selected views, (2) resolve issues on all the views inside the view controller.
To be honest, I am ignoring this feature and always try to create the constraints by myself. I only use the Clear Constraints option when it's necessary. That’s the only way to mastering Auto Layout.
If you want to see some AutoLayout examples, and how constraints are used in various situation click here.