Home > Articles > Programming > Mac and iOS Programming

This chapter is from the book

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

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

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

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:

  1. 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.
  2. With the button highlighted, select Editor, Align, Vertical Center in Container.
  3. Reselect the button, then choose Editor, Align, Horizontal Center in Container. The layout should now resemble Figure 16.5.
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

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

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:

  1. Drag a button to the storyboard, positioning it using the guide at the bottom of the view.
  2. 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

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:

  1. Drag two text views to the scene, stacking one on top of the other.
  2. Resize the text views to fill the scene horizontally, until the blue guides appear.
  3. 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.
  4. 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

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:

  1. Pin the height of the button so that at no point in time is it resized.
  2. 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.
  3. 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

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

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

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:

  1. Align all the buttons to the vertical center in the container. This keeps them centered vertically on the screen.
  2. 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.
  3. 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.
  4. Pin the Horizontal Spacing between Button A and Button B.
  5. 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.)
  6. 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

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

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).

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020