iOS Auto Layout: Tips and Techniques
More and more tools and systems are appearing that increase productivity and make a developer’s life easier. iOS Auto Layout is one such resource, providing developers with the ability to run two apps at the same time, on an iPad or any size iPhone.
This post will cover the basics of Auto Layout and will be useful for those who want to learn how to use it for writing applications for both iPhone and iPad.
You will learn how to use Size Classes, layout elements view in the preview, constraints creation, the constraints size change and how to look through libraries using Auto Layout.
What is Auto Layout?
Auto Layout is a dynamic system allowing developers to create user interfaces. It defines relationships between chosen elements and represents a high-powered, elastic system which defines the way views and UI controls interact with each other.
iOS Auto Layout is able to do things earlier technologies could only imagine. As another plus, it is compatible with many of Apple’s most amazing application programming interfaces (APIs), like motion effects, animations and sprites.
Specific libraries are designed to handle iOS Auto Layout:
- Apple Auto Layout
This is a framework designed to describe Cocoa and Cocoa Touch layouts in a reactive way. The framework is presently under development and exhibits premier alpha quality. However, significant changes may occur in the near future.
ReactiveCocoaLayout (RCL) has the following advantages over Auto Layout:
- The layout is explicit and linear: RCL has a linear form, making it easier to grasp and debug the steps it follows on its way.
- The layout is top-down: the layout of a view doesn't relate to a superview one unless the size or frame of the former is clearly absent from the latter's layout chain, creating a one-way relationship, which leads to a better encapsulation (no global priorities!) and reduced complexity. Bidirectional relationships are still affordable, but should be clarified.
- At runtime the layouts are conditional: RCL is based on the full capacity of ReactiveCocoa and signals allow dynamic disabling and re-enabling for entire layout chains (to hide and show views) without actually changing them.
- The animations are implicit: in order to animate a view’s frame settings, just add the animation method to the signal chain. You do not need to animate all constants.
- The use is incremental: RCL may be used within views, requiring no additional implementations.
- It is extensible by nature: RCL may easily be extended, using your functionality to make the framework behave differently.
- It is not a black box: in contrast to UIKit and AppKit, you may crack any bit to see why it behaves one way or another.
PureLayout extends NSArray, NSLayoutConstraint and UIView/NSView with a comprehensive Auto Layout API modeled after a sample of Apple’s own frameworks. PureLayout is a cross-platform Objective-C library for Swift, completely backward compatible with all versions of iOS supporting Auto Layout.
PureLayout provides a friendly interface for Auto Layout. It takes inspiration from AutoLayout UI options available in Interface Builder and delivers far more flexibility.
PureLayout defines view attributes used to build auto layout constraints. There are 5 specific types of attributes used throughout the API:
- ALMarginAxis available in iOS 8.0 and higher only
- ALMargin available in iOS 8.0 and higher only
Methods of PureLayout used for class UIView (NSView)
Click to show
- autoSetContent(CompressionResistance|Hugging)PriorityForAxis: - autoCenterInSuperview(Margins) // Margins variant iOS 8.0+ only - autoAlignAxisToSuperview(Margin)Axis: // Margin variant iOS 8.0+ only - autoPinEdgeToSuperview(Edge:|Margin:)(withInset:) // Margin variant iOS 8.0+ only - autoPinEdgesToSuperview(Edges|Margins)(WithInsets:)(excludingEdge:) // Margins variant iOS 8.0+ only - autoPinEdge:toEdge:ofView:(withOffset:) - autoAlignAxis:toSameAxisOfView:(withOffset:|withMultiplier:) - autoMatchDimension:toDimension:ofView:(withOffset:|withMultiplier:) - autoSetDimension(s)ToSize: - autoConstrainAttribute:toAttribute:ofView:(withOffset:|withMultiplier:) - autoPinTo(Top|Bottom)LayoutGuideOfViewController:withInset: // iOS only
Methods of PureLayout used for class NSArray
Click to show
// Arrays of Constraints - autoInstallConstraints - autoRemoveConstraints - autoIdentifyConstraints: // iOS 7.0+, OS X 10.9+ only // Arrays of Views - autoAlignViewsToEdge: - autoAlignViewsToAxis: - autoMatchViewsDimension: - autoSetViewsDimension:toSize: - autoSetViewsDimensionsToSize: -autoDistributeViewsAlongAxis:alignedTo:withFixedSpacing:(insetSpacing:)(matchedSizes:) - autoDistributeViewsAlongAxis:alignedTo:withFixedSize:(insetSpacing:)
Methods of PureLayout used for class NSLayoutConstraint
Click to show
+ autoCreateAndInstallConstraints: + autoCreateConstraintsWithoutInstalling: + autoSetPriority:forConstraints: + autoSetIdentifier:forConstraints: // iOS 7.0+, OS X 10.9+ only - autoIdentify: // iOS 7.0+, OS X 10.9+ only - autoInstall - autoRemove
Apple Auto Layout
Auto Layouts are necessary for any application today, whether it is written for an iPhone or iPad. This is due to constantly changing device sizes and new iOS features that make the available screen size dynamic for applications.
Auto Layout Terminology
Constraints are basic rules which specify the way different views must be set, when Auto Layouts are in use.
Settings Constraints to View
Setting Constraints in Interface Builder
This feature allows you to lay out views for different screen sizes recognized as a Size Class. Size Classes may be regular or compact. Whenever a constraint is determined for Auto Layouts, it may be determined specifically for a particular Size Class or generally for all the Size Classes.
Different Size Classes
Intrinsic Content Size
When doing design, Intrinsic Content Size is used to avoid ambiguity. Items like UILabels are able to adjust width automatically, which means they don't need Intrinsic Content Size to be defined.
Auto Layouts and Auto Resizing Masks
If you used Auto Resizing Masks, before using iOS Auto Layouts, you may benefit from the tips below to convert over to Auto Layouts. Auto Resizing masks may be translated into constraints with ease, if you set the property “translatesAutoresizingMaskIntoConstraints” to YES.
Adopting iOS Auto Layouts in the Application
Enabling iOS Auto Layouts: Prerequisites
For a demo, you should choose the Single View application from Xcode templates and create a Universal Application to test it easily on both iPhone and iPad devices.
Auto Layouts may be enabled by:
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
Step 1: Constraints Install
Let us assume there are two views, one over another. A different background color may be added to each one, making it easier to see Auto Layouts in operation.
a) adding constraints to the interface builder
Interface builder provides an opportunity for adding constraints to views in various ways. Some are interactive, such as control dragging or setting constraints between two views. When you open the storyboard, you will see three buttons: “Align”, “Pin” and “Resolve Auto Layout Issues” in the bottom toolbar of the editor on the right end.
Given as an example, there are two views of a view controller on the screenshot below. Let us call them views A and B.
To add Individual Constraints, there is a separate working scheme:
- choose view A;
- click on "Pin" button;
- deselect “Constrain to Margins”;
- expose values for spacing up to 10 on all four sides and choose lines for spacing;
- repeat steps 2-4 for view B;
- preview the results
As you can see, view B is not shown in the preview. The reason for that is there is not a proper relation between views A and B set.
You may also notice a red warning in the Document Outline, which means that certain constraints are missing, and therefore we are not providing enough constraints for iOS to lay out the views.
To resolve these issues, we may refer to Xcode interface builder.
In this particular case, for example, you need views A and B to have equal heights. This means “Equal Heights” constraints should be added to resolve this issue.
To add “Equal Heights” constraints, do the following:
- choose views “A” and “B”;
- click on the "Pin" button;
- choose “Equal Heights”.
Hereby, the layout issues have been resolved and you are able to preview views A and B having equal heights now.
Previewing after Adding Equal Heights Constraints
b) adding constraints of iOS Auto Layout programmatically
You may set constraints programmatically, and may learn this from the Apple guide.
Step 2: Changes Preview
Xcode interface builder provides a useful tool for inspecting layouts on various devices without running the application.
Opening Preview Pane
Step 3: Resolving Auto Layout Issues
Interface Builder notifies of ambiguities, like unperformed or missing constraints, by showing warnings and adding orange borders around the frames.
Alexander, iOS Developer at Visual Craft