* 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:
- Apple: Working with Constraints in Interface Builder
- 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.
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.
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.
- StackOverflow: What is the difference of intrinsic size vs system width/height constraints?
- Apple: Setting the Placeholder Intrinsic Size for a Custom View
- Apple: Implementing a Custom View to Work with Auto Layout
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:
- StackOverflow: Difference between Frame Rectangle and Alignment Rectangle
- Apple: Layout Operates on Alignment Rectangles, Not on Frames
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.
- Apple: Adopting Auto Layout
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.
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:
- Select view A.
- Click on Pin button at the bottom right of the editor.
- Unselect “Constrain to Margins”.
(This is because the superview will have some inherent margins which we don’t care for now.).
- Set the values for spacing to 10 on all four sides and select the spacing lines (the dotted lines will turn solid).
- Repeat steps 2-4 for view B.
- Preview the effects (See section 3 below).
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).
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:
- Select views A and B.
- Click on Pin button at the bottom right of the editor.
- 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.
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 🙂
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.
- Apple: Resolving Auto Layout Issues
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
- Content Hugging Priority and Content Compression Resistance
- StackOverflow: Cocoa Autolayout: content hugging vs content compression resistance priority
- Ray Wenderlich Forum: Ch 3. Beginning Auto Layout Content Hugging Explanation???
- Multiplier, Constant and Priority field
- Stretchable Views: This is not completely related to Auto Layout but also not completely different if you need stretchable views. Hence its here 🙂
- Apple: WWDC 2015: Mysteries of Auto Layout, Part 1
- Apple: WWDC 2015: Mysteries of Auto Layout, Part 2
- Ray Wenderlich: Auto Layout Tutorial Part 1: Getting Started
- Ray Wenderlich: Auto Layout Tutorial Part 2: Constraints