Using Autolayout in Xcode

When you add an object from the object library in Xcode, the position of the object within your view needs to be in the same position when viewing on different device widths. This article will look at using Autolayout in Xcode 8.

As an example, here is a label that has been centred in the view on an iPhone 6s.

Using Autolayout in Xcode

When running the build on an iPhone 7 Plus, you can see that the label is slightly off-centre.

Using Autolayout in Xcode

Adding Constraints

In Xcode, you can add constraints that will dynamically calculate the size and position of the object in your views no matter when screen size you view the application on. Now only can the screen size change dependant on the type of phone, but also when the device rotates from portrait to landscape or vice versa, or viewing the Split View on an iPad.

So how do we add these constraints? First of all, ensure that you have your object selected you would like to add a constraint to.

Next, choose the Align option located in the bottom right hand corner of the view.

Using Autolayout in Xcode

Already we can see that there are handy options to vertically and horizontally align the object. Check these two options and click on the Add 2 Constraints button.

Using Autolayout in Xcode

Look at the menu under the View Controller Scene and you’ll notice that the constraints have been successfully added to the view.

Using Autolayout in Xcode

Resolve Auto Layout Issues

Take note of the orange lines that have been added to your view.

Using Autolayout in Xcode

The orange lines indicate that the frame of one of the items affected by this constraint is not in the correct position based on the current set of constraint.

To resolve these Auto Layout issues, head to the bottom right hand corner of the view again and click on the Resolve Auto Layout Issues menu item, which should be the farthest icon to the right.

You will want to select the Update Constraints option. You can choose either selected view or all views.

Using Autolayout in Xcode

The orange lines will now disappear, and your constraints will show on the view.

Now when running the application on the iPhone 7 Plus again, the label text will be centred correctly.

Using Autolayout in Xcode

While this is just a simple example of centring a label, however knowing about Auto Layout is a key aspect of learning application development in Xcode. You can use this functionality to align images, buttons and other objects.