Auto Layouts in iOS

* This tutorial uses Xcode 6 and iOS 8 *

Auto Layouts today are inevitable for any application. Be it an iPhone or an iPad application. That is because the device sizes are ever changing and also because of new iOS features like multi tasking for iPad makes the available screen size for your application dynamic. To take advantage of all these things, we will have to use Auto Layouts in our applications. In other words, don’t go away unless you finish reading this if it is new to you 🙂

What is Auto Layout?

Auto Layout is a system that lets you lay out your app’s user interface by creating a mathematical description of the relationships between the elements. You define these relationships in terms of constraints either on individual elements, or between sets of elements. Using Auto Layout, you can create a dynamic and versatile interface that responds appropriately to changes in screen size, device orientation, and localization.

– Apple: Auto Layout Guide

Auto Layout Terminology

What are Constraints?

Constraints are basically rules that specify how different views should be positioned while using Auto Layouts.

The fundamental building block in Auto Layout is the constraint. Constraints express rules for the layout of elements in your interface; for example, you can create a constraint that specifies an element’s width, or its horizontal distance from another element. You add and remove constraints, or change the properties of constraints, to affect the layout of your interface.

When calculating the runtime positions of elements in a user interface, the Auto Layout system considers all constraints at the same time, and sets positions in such a way that best satisfies all of the constraints.

– Apple: Auto Layout Concepts

Settings Constraints to views:
  1. Apple: Working with Constraints in Interface Builder
  2. Apple: Working with Auto Layout Programmatically

Settings constraints programmatically uses Strings in the Visual Format Language: Apple: Visual Format Language

The constraints are installed on generic or specific size classes.

AL_SetConstraints
Setting Constraints in Interface Builder

What are Size Classes?

Size Classes are a feature that allows you to layout views for various screen sizes generalised as a Size Class. Size Classes are either Regular or Compact. Whenever any constraint is defined for Auto Layouts, we can specify them for any particular Size Class or generalise for all the Size Classes. iOS uses the below size classes for Auto Layouts and allows us to choose out of the below options while working on storyboards and while setting constraints for the views.

Size Classes
Different Size Classes

Read more about Size Classes here:

Frame and Bounds and Centre Properties

Bounds: Bounds contain the view’s width and height properties.

Frame: Frame corresponds to the position of a view within it’s superview. It has x, y co-ordinates as well as width-height of the view. (This would be different than the view’s bounds if the view is rotated or some transformation is applied to the view.)

Centre: The views centre is the central point in the view within the superview.

Not clear? Follow the below links.

What is Intrinsic Content Size?

Defining an Intrinsic Content Size helps avoiding ambiguity during design time. System items such as UILabels adjust width automatically and hence doesn’t require Intrinsic Content Size to be defined. While for Custom views you can override the function intrinsicContentSize to return the correct size during runtime.

Frame Rectangle and Alignment Rectangle

Auto Layout operates on the so called Alignment Rect. The alignment rect considers the required portion of the view like Label in a Button and excludes any ornamentation like Shadows.

I am not getting this:

Auto Layouts and Auto Resizing Masks

In case you have been working Auto Resizing Masks before using Auto Layouts, you can use the below guide to adopt Auto Layouts. Auto Resizing masks can be easily translated into constraints by setting the property translatesAutoresizingMaskIntoConstraints to YES.


Adopting Auto Layouts in your Application

Pre-Requisites: Enabling Auto Layouts

For this demo I am choosing the Single View application from Xcode templates and creating a Universal Application so that it can be tested for both iPhone as well as iPad devices.

Once we an application to work with, enable Auto Layouts by:
Select Main.storyboard -> Utilities bar -> File Inspector -> under Interface Builder Document section: Select Use Auto Layout and Use Size Classes.

Enabling Auto Layouts and Size Classes
Enabling Auto Layouts and Size Classes

1. Installing Constraints

For this example, Let us assume we have two views one on top of another. You can set different background colour to the views to make it easy to see Auto Layouts in action!

a) Adding Constraints In Interface Builder
Interface builder allows you to add constraints to the views in multiple ways. There are interactive ways such as control dragging from a view to a parent or adjacent view to set constraints between the two views.

Once the storyboard is opened, the bottom toolbar of the editor will have three buttons on the right end “Align”, “Pin” and “Resolve Auto Layout Issues”.

In this example, the view controller has two views that looks like the screenshot below. Lets call the two views A and B. (To add a view to the view controller, Open the “Utilities” bar (Top Right End button), Open the “Object Library” search for a View and drag and drop on the storyboard. Resize and adjust frame manually or by using the Size Inspector. Change colour by selecting the view and using the Attributes Inspector.)

Adding Individual Constraints:

  1. Select view A.
  2. Click on Pin button at the bottom right of the editor.
  3. Unselect “Constrain to Margins”.
    (This is because the superview will have some inherent margins which we don’t care for now.).
  4. Set the values for spacing to 10 on all four sides and select the spacing lines (the dotted lines will turn solid).
  5. Repeat steps 2-4 for view B.
  6. Preview the effects (See section 3 below).
AL_Eg_Step3
Adding Constraints

You will notice that the view B is not seen in the preview. This is because we have not set an proper relation between views A and B and also if you notice the red warning in the Document Outline, it tells that some constraints are missing which means that we are not providing enough constraints for the iOS to layout the views. To resolve the issues we can ask Xcode to resolve issues for us as described below (See section 4 below).

AL_Eg_Step2
Previewing after Setting Constraints

For this example, let’s see you need the two views A and B to have equal heights, you can add “Equal Heights” constraints to resolve this issue.

Adding Equal Heights Constraints:

  1. Select views A and B.
  2. Click on Pin button at the bottom right of the editor.
  3. Select “Equal Heights”.

Now, if you observe, the layout issues have been resolved and you can preview that the views A and B now have equal heights.

AL_PreviewPane
Previewing after Adding Equal Heights Constraints

b) Adding Constraints Programatically

You can also programatically set the constraints. This is described in the below Apple guide.

3. Previewing the changes

Xcode provides a very useful tool to inspect your layout in various devices without actually having to run the application! Yes 🙂

AL_PreviewPane
Opening Preview Pane

4. Resolving Auto Layout Issues

Interface Builder shows ambiguity such as unfulfilled or missing constraints by providing warnings and by adding orange borders around frames. The below document explains how to resolve such issues in various cases.

Where to go from here?

Going through the below references and trying out examples for couple scenarios would be the next best thing to do. Auto Layouts are convenient. But if you do not understand how they work or even if you don’t know what are the different features available for Auto Layouts, it can turn to be a real PITA in some scenarios.

Other Interesting Things

  1. Content Hugging Priority and Content Compression Resistance
    1. StackOverflow: Cocoa Autolayout: content hugging vs content compression resistance priority
    2. Ray Wenderlich Forum: Ch 3. Beginning Auto Layout Content Hugging Explanation???
  2. Multiplier, Constant and Priority field
    1. Apple: Editing Auto Layout Constraints
  3. Stretchable Views: This is not completely related to Auto Layout but also not completely different if you need stretchable views. Hence its here 🙂
    1. Apple: View Architecture Fundamentals: Stretchable Views

References

  1. Apple: Auto Layout Guide
  2. Apple: Auto Layout By Example

Developer Videos

  1. Apple: WWDC 2015: Mysteries of Auto Layout, Part 1
  2. Apple: WWDC 2015: Mysteries of Auto Layout, Part 2

Tutorials

  1. Ray Wenderlich: Auto Layout Tutorial Part 1: Getting Started
  2. Ray Wenderlich: Auto Layout Tutorial Part 2: Constraints

Further Reads

  1. ObjC.IO: Advanced Auto Layout Toolbox
  2. Big Nerd Ranch: iOS Auto Layout: Fun Facts and Tips
Advertisements

2 thoughts on “Auto Layouts in iOS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s