Using Auto Layout
As already mentioned, Auto Layout enables us to build responsive interfaces without writing a line of code. Because of that, our first tutorial is a series of examples that you can follow along with, rather than a project that we build. I’ve included several sample storyboard files in this hour’s Projects folder, but you should definitely get yourself into IB and attempt the examples on your own.
The Language and Tools of Auto Layout
When I see something with Auto in the name, I expect that it is going to do things for me: automatically. Auto Layout lives up to this, but not without a reasonably long “getting to know you” phase. To use Auto Layout effectively, you must understand the terminology and know where to look for the tools. We spend the next few minutes getting into details, and then walk through a few examples that should get you started on the way to mastery. (Perhaps of archery or speed skating. Auto Layout if you’re lucky.)
Constraint Basics
Auto Layout works by building a series of constraints for your onscreen objects. Constraints define placement of objects, distances between objects, and how flexible these relationships are. A vertical constraint for a button, for example, might be along the lines of “keep X many points of space between this object and the top of the screen” or “keep object Y vertically centered in the view.” Unfortunately, the language used for positioning can be a bit confusing; you may not be familiar with these terms:
- Leading: The “front” or left side of an object.
- Trailing: The “back” or right side of an object.
- Superview: The view that contains an object. In our examples, this is the “view” that makes up the scene itself.
For example, try adding a button to the window in the Empty.storyboard file; make sure is located toward the top-left side of the view and that you’ve resized the button slightly. Notice that parallel to the button in the document outline hierarchy a new Constraints entry shows up, as well as a Constraints item within the button object itself, as shown in Figure 16.2.
Figure 16.2. The Constraints object represents the positioning relationships within a view, or Constraints on the UI elements themselves.
Navigating the Constraints Objects
Within the view’s Constraints object are two constraints: horizontal space and vertical space constraint. The horizontal constraint states that the left side of the button will be a certain number of points from the left edge of the view. This is known as the leading space (versus the space between the right side and the edge of the view, which is called the trailing space). The vertical constraint is the distance from the top of the view to the top of the button.
What constraints are added depend on where the object is in relation to its containing view. Xcode does its best to choose what constraints make the most sense. If you position a button near the bottom of the view, for example, it will add a constraint for the distance between the bottom of the button and the bottom of the view.
Constraints, however, are more than just entries that tie an object to the view it is within. They can be flexible, ensuring that an object maintains at least or at most a certain distance from another object, or even that two objects, when resized, maintain the same distance between one another.
Constraints that set a specific size or distance between objects are called pinning. The flexibility (or inflexibility of a constraint) is managed by configuring a relationship.
This brings us to the second constraint object in the document outline: constraints on the object itself, not on its positioning. When you resize a user interface (UI) element or set constraints on how the content within it is positioned, Xcode adds (or modifies) a constraint object within the UI element itself. These constraints determine the width or height of the element. Not surprisingly, when you’ve got dozens of components in your UI, you’ll have lots of constraints in your document outline.
Viewing and Editing Constraints via the Size Inspector
While sorting through constraints in the document outline can be a pain, you can quickly view all the constraints applied to an element (whether located in the Constraints object on the view the element is in, or within the UI element itself) within the Size Inspector (Option-Command-5). For example, if you’ve added a resized button to the storyboard, opening the Size Inspector should look something like Figure 16.3. Here horizontal and vertical positioning for the button are represented as constraints, as well as the width of the button.
Figure 16.3. Use the Size Inspector to view your constraints.
Using the gear menu to the right side of each constraint to do one of three things. First, you can select and edit a constraint. For example, if you pick a width constraint and choose Select and Edit, Xcode jumps you into the Attributes Inspector, where you can see and adjust the details of the constraint, as shown in Figure 16.4.
Figure 16.4. Use the Attributes Inspector to edit constraints.
The Relation drop-down determines what the constraint is trying to do. Is it trying to keep a distance or size equal to a value? Greater than or equal to it? Less than or equal? You choose the relation that gives your interface the flexibility you need. With each relation, you can also set a constant. This is a measurement, in points, that the relationship will be maintaining.
You’ll also notice a Priority slider and a Standard check box (sometimes) appear in the editor. The Priority slider determines how “strong” the constraint relationship is. There may, for example, be instances when multiple constraints must be evaluated against one another. The priority setting determines the importance of any given constraint. A value of 1000 is a constraint that is required. If you move the Constraint slider, Xcode shows a description of what to expect at a given constraint priority.
The Standard check box lets Xcode use its internal database of spacing to set the recommended space between two objects. This, in many cases, is preferred because it ensures a consistent interface.
In a few minutes, we’ll make use of the editor to configure a few relationships. Trust me, it makes more sense once you get started.
The other options available in the gear menu in the Size Inspector are Promote to User Constraint and Delete. With Promote to User Constraint, you can select a constraint that you didn’t add manually, turn it into a user constraint. The other option, Delete, removes the constraint from the Storyboard. Remember that there must be constraints to describe the object’s position complete, so if you delete a constraint, don’t be surprised to see Xcode add a new constraint back into the storyboard to fill in missing positioning details.
Content Hugging and Content Compression Resistance
When viewing an interface object with the Size Inspector, you probably noticed the settings Content Hugging Priority and Content Compression Resistance Priority. These features are related to Auto Layout, but what do they do?
When inspecting an object that is within an Auto Layout XIB, these settings control how closely the sides of an object “hug” the content in the object and how much the content can be compressed or clipped. Imagine a button that you want to expand horizontally, but not vertically. To allow horizontal expansion, you’d set horizontal hugging is a low priority. To keep it from growing vertically, you set vertical hugging to a high priority.
Similarly, the content (the button label) should not be compressed or clipped at all, so the content compression resistance settings for both horizontal and vertical compression should be very high priority.
You will not often need to adjust these settings beyond their defaults, which IB adds for you.
Example One: Centering Constraints
Let’s look at a very simple example: a button that stays centered regardless of whether you use a 3.5” or 4” iPhone (or any iPad), or rotates between portrait and landscape orientations. To do this, begin by adding and positioning the button:
- If you already have a push button added to a window in the Empty.storyboard file, you’re in good shape. If not, open the file and add one now.
- With the button highlighted, select Editor, Align, Vertical Center in Container.
- Reselect the button, then choose Editor, Align, Horizontal Center in Container. The layout should now resemble Figure 16.5.
Figure 16.5. Align the button to the vertical and hortizontal centers.
The constraints that you’ve added show up as dark blue lines in the layout. Dark blue lines indicate user constraints; that is, you added the alignment constraints to the system.
Take a moment to view the constraints on the button via the Size Inspector. Select the button, then press Command-Option-5; the Size Inspector should show at least two constraints (more if you changed the size of the button), as shown in Figure 16.6.
Figure 16.6. Toggle the size of the screen.
Now try toggling the size of the screen between 3.5” and 4”, using the toggle icon shown in Figure 16.6. The button should stay centered, regardless of the screen size. The final test is to try the interface in another orientation.
Make sure that the document outline is visible, select the view controller for the scene. Open the Attributes Inspector (Option-Command-4) and choose Landscape from the Orientation drop-down menu. IB updates to show the interface in landscape mode. Assuming your constraints are correct, the button should also properly center itself in the view, as demonstrated in Figure 16.7.
Figure 16.7. The button centers itself, regardless of orientation and screen size.
That was pretty simple, wasn’t it? Of course, not all your applications will consist of just a single button (only the best ones). For that reason, we cover a few more examples, starting with resizing controls.
Example Two: Expanding Controls
A common design problem is where you have a series of controls on the screen and they need to expand to fill the size of the screen (or, in the case of a 3.5” iPhone display, properly shrink to fit on the screen). For example, let’s create an interface with two text views at the top and a button at the bottom. The button should always remain anchored at the bottom, but should grow horizontally to fill the width of the display. The text views should grow or shrink vertically, and expand horizontally to fill the screen.
Creating the Interface
Starting from a fresh copy of Empty.storyboard, follow these steps:
- Drag a button to the storyboard, positioning it using the guide at the bottom of the view.
- Resize each side of the button by dragging toward the side of the view, and then release when you see the blue guide appear.
By using the guides in steps 1 and 2, you’ve created three constraints that anchor to the side and bottom margins of the view, as shown in Figure 16.8.
Figure 16.8. These three constraints make the button resize and stay anchored at the bottom, regardless of the screen size or orientation.
The constraints that have been automatically created are a good start for the button. These ensure that the sides of the button are always an equal distance from the sides of the view, regardless of the orientation. The same goes for the distance from the bottom of the view to the bottom of the button.
Next, add two text views to the scene:
- Drag two text views to the scene, stacking one on top of the other.
- Resize the text views to fill the scene horizontally, until the blue guides appear.
- Size the text views vertically until the guides appear to keep the views from overlapping the button, one another, or the top margin of the scene.
- Set the color of the text views to something other than white so that they are easier to see. Your finished view should look like Figure 16.9.
Figure 16.9. You’ve added three UI elements and quite a few system constraints.
The top text view has constraints generated to attach it to the top of the view and the sides of the view. The bottom text view has constraints that keep it a set distance from the sides of the view and the button at the bottom. Between the two text views is a constraint that keeps them a set distance apart. Finally, one of the text views will have a height constraint applied.
Setting the Constraints
Try resizing and rotating the display. What you’ll notice is that resizing it vertically (switching between 3.5” and 4” screens) likely works okay. What definitely doesn’t is rotating to landscape. In landscape mode, one of the text views will shrink so much that it isn’t even visible. To make the scene work right, you need to set some additional constraints.
Specifically, you need to accomplish these things:
- Pin the height of the button so that at no point in time is it resized.
- Pick one of the text views to be the first to shrink when the size changes. We set this view so that its height is greater than or equal to the smallest size we want it to reach. I will use the top view for this purpose and set its minimum height to 100 points or greater.
- Set a fixed width on the bottom text view (I’ll use 210 points) so that it doesn’t change size. But, we need to set its priority to less than 1000 (the default). This lets the text view change sizes in an extreme situation. That “extreme situation” would otherwise occur in landscape mode where the top view would try to maintain a height of 100 points but the bottom view’s fixed height of 210 would force a condition where both can’t hold.
Begin by selecting the button and choosing, Editor, Pin, Height from the menu bar. Simple enough!
Next, choose the top text view and choose Editor, Pin, Height (again). You’ve just created a height constraint, but it needs to be adjusted so that it is flexible. Select the height constraint within the design view (or within the size inspector), and then open the Attributes inspector.
Using the Relation drop-down, choose Greater Than or Equal. Set the constant to 100 (the text view must be 100 points in height or greater) and leave the priority alone. Your configuration should look like Figure 16.10.
Figure 16.10. Set the relation for the height constraint.
Now the top text view will shrink when it needs to, but it can also grow; in fact, until a constraint is set on the bottom text view, it can grow too large, pushing the bottom text view until it is too small in any orientation.
Select the bottom text view and again add a height constraint (Editor, Pin, Height, yet again). Select the constraint and make sure that the relation is set to Equal with a constant around 210, as shown in Figure 16.11. This time, however, set the priority down to 999. This makes the constraint turn into a dotted line (visible in Figure 16.11) showing that the constaint will try to be maintained, but, if necessary, it can resize to avoid violating other constraints.
Figure 16.11. Set a height constraint with a priority lower than 1000 to enable the text view to change sizes if absolutely necessary.
Go ahead and try resizing the view between 3.5” and 4” iPhone screen sizes and rotating to landscape mode. Everything should work like a charm, with the top text view resizing when needed and the bottom text view resizing when it absolutely has to.
Example Three: Variable and Matching Sizes (and Auto Layout Craziness!)
Okay, one more quick exercise to round things out. I promise this one is easier than the last. This time, we add three buttons in a horizontal line, and we add enough constraints to make the buttons all resize equally when we shift to a landscape mode.
Let’s make this happen! Create a new copy of the Empty.storyboard document, and then drag three buttons into the horizontal line on the screen. Label the buttons Button A, Button B, and Button C, as shown in Figure 16.12.
Figure 16.12. Add three buttons, nothing more.
You now know enough to make one of the buttons resize, but how could we constrain them so that all the buttons resize to fill in the screen in landscape mode? These are the constraints that I came up with:
- Align all the buttons to the vertical center in the container. This keeps them centered vertically on the screen.
- Pin the Leading Space of Button A to the superview (the edge of the view). This is unnecessary if you used a guide to align the left edge of the button and Xcode already added a constraint tying the edge of the button to the edge of the view.
- Pin the Trailing Space of Button C to the superview. Like the first constraint, you don’t technically need this one if you aligned the right side of the button to a guide and Xcode added a constraint for you.
- Pin the Horizontal Spacing between Button A and Button B.
- Pin the Horizontal Spacing between Button B and C. (If we stopped here, the center button (Button B) would stretch while the other buttons would stay the same size.)
- Pin the buttons so that they all share the same width. (Select all the buttons, and then choose Editor, Pin, Widths Equally.)
Use the Editor menu to add these constraints to your project; you should know how to do it by now. There is no need to adjust the priority or relationships in this case. Your finished layout will hopefully be similar to Figure 16.13 (one of the = constraints may be on a different button. This is fine). Save your work before continuing.
Figure 16.13. Add these constraints to your scene.
Now, here’s where it gets interesting (wake up!). When you rotate the view to landscape, all the buttons should resize equally and fill in the space across the screen, as shown in Figure 16.14.
Figure 16.14. The buttons’ constraints force them to spread out across the screen and match sizes.
This is exactly what we want. But, what happens when you rotate back to a vertical position? Chances are that the buttons get all weird looking and overlap. Switch back and forth between horizontal and landscape orientations, and they may get even worse.
So, what’s going on here? Xcode is being a pain, that’s what. When you switch to landscape, it is rewriting the constraints as if you designed the view in landscape mode. You actually lose work and constraint logic depending on how the complex your interface is.
To deal with this bit of insanity, just use Command-Z to undo the switch to landscape orientation after validating that the interface looks okay. As long as it looks good in your original view and when it first switches to landscape, you’re in good shape. The compiled view used in your actual application will work just fine (even if it switches back and forth between portrait and landscape orientations).