Introduction to “Life is short. Build stu Auto Layout ... · Obviously, we want the app to look...

16
Introduction to Auto Layout 3 “Life is short. Build stuthat matters.” – Siqi Chen

Transcript of Introduction to “Life is short. Build stu Auto Layout ... · Obviously, we want the app to look...

Page 1: Introduction to “Life is short. Build stu Auto Layout ... · Obviously, we want the app to look good on both 3.5-inch & 4-inch iPhone, as well as, in both portrait & landscape orientation.

Introduction to Auto Layout

3“Life is short. Build stuff that matters.”

– Siqi Chen

Page 2: Introduction to “Life is short. Build stu Auto Layout ... · Obviously, we want the app to look good on both 3.5-inch & 4-inch iPhone, as well as, in both portrait & landscape orientation.

Copyright © 2015 AppCoda Limited All rights reserved. Please do not distribute or share without permission. No part of this book or corresponding materials (such as images or source code) may be distributed by any means without prior written permission of the author.

All trademarks and registered trademarks appearing in this book are the property of their respective owners.

i

Page 3: Introduction to “Life is short. Build stu Auto Layout ... · Obviously, we want the app to look good on both 3.5-inch & 4-inch iPhone, as well as, in both portrait & landscape orientation.

Introduction to Auto Layout

Wasn’t it fun to create the Hello World app? Before we move onto building a real app, we’ll take a look at Auto Layout in this chapter.

Let’s get started.

Auto Layout is a constraint-based layout system. It allows developers to create an adaptive UI that responds appropriately to changes in screen size and device orientation. Some beginners find it hard to learn and avoid using it. Believe me, once

you get comfortable with it, Auto Layout will be one of your greatest tools, one that you won’t be able to live without when developing an app.

You may wonder why I talk about Auto Layout rather than jumping right into writing a real app. Starting with Xcode 6, learning Auto Layout will be inevitable. I want to help you build a solid foundation on how to lay out a user interface. With the release of iPhone 6 and 6 Plus, Apple’s

50

Figure 3-1. The app UI looks different when running on iPhone 4s (3.5-inch)

Page 4: Introduction to “Life is short. Build stu Auto Layout ... · Obviously, we want the app to look good on both 3.5-inch & 4-inch iPhone, as well as, in both portrait & landscape orientation.

iPhones are available in different screen sizes. Without using Auto Layout, it would be very hard for you to build an app that supports all screen resolution. Throughout this chapter, you will get to know the power of Storyboard and Auto Layout.

Why Auto Layout?Okay, let me give you an example and hopefully you’ll have a better idea why Auto Layout is needed. Open the HelloWorld project you’ve built in chapter 1. Instead of running the app on iPhone 5s simulator, run it using the iPhone 4s simulator, which is a 3.5-inch device.

You’ll end up with the results illustrated in figure 3-1. It turns out that the button isn’t centered when running on iPhone 4s.

Let’s try one more thing.

Click the Stop button and run the app using the iPhone 5s simulator. After the simulator launches, select Hardware > Rotate Left (or Rotate Right) from the menu. This rotates the device to landscape mode. Again, the Hello World button is not centered.

Why? What’s wrong with it?

First, you should understand that iPhone 5/5s and 4s have different screen dimensions. For iPhone 5/5s, the screen in portrait mode consists of 320 points (or 640 pixels) horizontally and 568 points (or 1136 pixels) vertically. For iPhone 4s, the screen consists of 320 points (or 640 pixels) and 480 points (or 960 pixels).

Why Points instead of Pixels?

Back in 2007, Apple introduced the original iPhone with a 3.5-inch display with a resolution of 320x480. That is 320 pixels horizontally and 480 pixels vertically. Apple retained this screen resolution with the succeeding iPhone 3G and iPhone 3GS. Obviously, if you were building an app at that time, one point corresponds to one pixel. Later, Apple introduced iPhone 4 with retina display. The screen resolution was doubled to 640x960 pixels. So one point corresponds to two pixels for retina display.

51

Page 5: Introduction to “Life is short. Build stu Auto Layout ... · Obviously, we want the app to look good on both 3.5-inch & 4-inch iPhone, as well as, in both portrait & landscape orientation.

The point system makes our developers’ lives easier. No matter how the screen resolution is changed (say, the resolution is doubled again to 1280x1920 pixels), we still deal with with points and the base resolution (i.e. 320x480 for iPhone 4/4s or 320x568 for iPhone 5/5s). The translation between points and pixels is handled by iOS.

Figure 3-2. Screen dimensions for iPhone 5/5s and 4s

Without using Auto Layout, the position of the button we lay out in the Storyboard is fixed. In other words, we “hard-code” the frame origin of the button. In our example, the “Hello World” button’s frame origin is set to (120, 269). Therefore, whether you’re using a 3.5-inch or 4-inch simulator, iOS draws the button in the specified position. Figure 3-2 illustrates the frame origin on different devices. This explains why the “Hello World” button cannot be displayed properly on a 3.5-inch iPhone and in landscape orientation.

52

Page 6: Introduction to “Life is short. Build stu Auto Layout ... · Obviously, we want the app to look good on both 3.5-inch & 4-inch iPhone, as well as, in both portrait & landscape orientation.

Obviously, we want the app to look good on both 3.5-inch & 4-inch iPhone, as well as, in both portrait & landscape orientation. This is why we need to learn Auto Layout. It’s the answer to the screen layout issues we just talked about.

Auto Layout is All About ConstraintsAs mentioned before, Auto Layout is a constraint-based layout system. It allows developers to create an adaptive UI that responds appropriately to changes in screen size and device orientation. Okay, it sounds good. But what does the term “constraint-based layout” mean? Let me put it in a more descriptive way. Consider the “Hello World” button again, how do you describe its position if you want to place the button at the center of the view? You would probably describe it like this:

The button should be centered both horizontally and vertically, regardless of the screen resolution and orientation.

Here you actually define two constraints:

• center horizontally

• center vertically

These constraints express rules for the layout of the button in the interface. Auto Layout is all about constraints. While we describe the constraints in words, the constraints in Auto Layout are expressed in mathematical form. For instance, if you’re defining the position of a button, you might want to say “the left edge should be 30 points from the left edge of its containing view.” This translates to button.left = (container.left + 30). That’s all you need to know. Fortunately, we do not need to deal with the formulas.

Okay, that’s quite enough of the Auto Layout theory.

Now let’s see how to center the “Hello World” button regardless of the screen size and orientation (portrait / landscape).

53

Page 7: Introduction to “Life is short. Build stu Auto Layout ... · Obviously, we want the app to look good on both 3.5-inch & 4-inch iPhone, as well as, in both portrait & landscape orientation.

Using Auto Layout to Center a ButtonXcode provides two ways to use Auto Layout:

• Auto layout menu• Control-drag

We’ll demonstrate both approaches in this chapter. Let’s begin with the Auto Layout menu. Open the “Main.storyboard” of your HelloWorld project. At the bottom-right corner of Interface Builder, you’ll find the Auto Layout menu. The buttons in the menu are different functions associated with Auto Layout.

Figure 3-3. Auto layout menu

Each button has its own function:

• Align – Create alignment constraints, such as aligning the left edges of two views.

• Pin – Create spacing constraints, such as defining the width of a UI control.

• Issues – Resolve layout issues.

• Resizing – Specify how resizing affects constraints.

To center the “Hello World” button, you need to first select it and then click the Align icon in the Auto Layout menu. In the

Here is a quick tip when working with Storyboard, especially if you’re working with Xcode on a laptop. From the menu, choose View > Navigators > Hide Navigator or simply press command-0 key. This hides the project navigator and gives you more screen space for editing your storyboard.

54

Page 8: Introduction to “Life is short. Build stu Auto Layout ... · Obviously, we want the app to look good on both 3.5-inch & 4-inch iPhone, as well as, in both portrait & landscape orientation.

pop-over menu, check both “Vertical center in container” and “Horizontal center in container” options. Next, click the “Add 2 Constraints” button.

You should now see a set of constraint lines. If the constraint line is in blue, it indicates that your view layout is being configured correctly and there is no ambiguity. If you want to check out the constraints, you can view them in the Document Outline and Size Inspector. Refer to figure 3-5 for details.

Figure 3-5. View the constraints in Document Outline and Size Inspector

55

Figure 3-4. Adding constraints using Align button

Page 9: Introduction to “Life is short. Build stu Auto Layout ... · Obviously, we want the app to look good on both 3.5-inch & 4-inch iPhone, as well as, in both portrait & landscape orientation.

Okay, you’re ready to test the app again. You can click the Run button to launch the app on both iPhone 4 and 5 simulators. Even if you run the app on iPhone 6 & 6 Plus, the app should look great.

Resolving Layout IssuesThe layout constraints that we have just set are perfect. But that is not always the case. Xcode is intelligent enough to detect any constraint issues.

Try to drag the Hello World button to the lower-left part of the screen. Xcode immediately detects some layout issues and the corresponding constraint lines turns orange indicating a misplaced item.

Auto layout issues occur when you create ambiguous or conflicting constraints. Here we said the button should be vertically and horizontally centered. However, the button is now placed at the lower-left corner of the view. Xcode found this confusing and therefore uses orange lines to indicate layout issues.

With any layout issue, the Document Outline view will display a disclosure arrow (red/orange). Click the disclosure arrow to see a list of the issues. Xcode is smart enough to resolve the layout issues for us. Click the indicator icon next to the issue and a pop-over shows you a number of solutions. In this case, select the “Update Frame” option and click “Fix Misplacement” button. The button will then be moved to the center of the view.

56

Figure 3-6. Interface Builder uses orange/red lines to indicate Auto Layout issues

Page 10: Introduction to “Life is short. Build stu Auto Layout ... · Obviously, we want the app to look good on both 3.5-inch & 4-inch iPhone, as well as, in both portrait & landscape orientation.

Figure 3-7. Resolving misplacement issue

The kind of layout issue may be unusual. I just wanted to demonstrate how to find the issues and fix them. As you build your UI using Auto Layout either in your own app or working through the exercises, you will know how to resolve layout issues easily and quickly.

57

Page 11: Introduction to “Life is short. Build stu Auto Layout ... · Obviously, we want the app to look good on both 3.5-inch & 4-inch iPhone, as well as, in both portrait & landscape orientation.

Previewing StoryboardSo far we have only used the simulators to test the UI changes. Well, Xcode’s built-in simulators are great. But it’s not the best way to experiment with your app’s UI. Xcode 6 offers a Preview feature for developers to get a first look of the UI right in Xcode.

In Interface Builder, open the Assistant pop-up menu > Preview (1). Now press and hold shift+option key, then click Main.storyboard (Preview). You can refer to figure 3-8 for the steps.

You’ll be prompted to choose where to display the preview. Double-click the + button right next to the main area so that the preview will open in Assistant Editor.

Xcode will display a preview of your app’s UI in the assistant editor. By default, it shows you the preview on a iPhone 4-inch device. You can click the + button at the lower-left corner of the assistant editor to get a preview of iPhone 3.5-inch. If you want to see how the screen will look like in landscape orientation, simply click the rotate button. The Preview

58

Figure 3-8. Assistant Pop-up Menu

Figure 3-9. Select the Assistant Editor area

Page 12: Introduction to “Life is short. Build stu Auto Layout ... · Obviously, we want the app to look good on both 3.5-inch & 4-inch iPhone, as well as, in both portrait & landscape orientation.

feature is extremely useful for designing your user interface. You can make changes to the storyboard (say, adding another button to the view) and simultaneously see how those changes look in the preview. This will save you from loading the app in the simulator time and time again, particularly if you just want to test a simple UI change.

Figure 3-10. Previewing storyboard in the Assistant Editor

Adding a LabelNow that you have some idea about Auto Layout. Let’s try to add a label to the lower-right part of the view. As you know, the iPhone 5 is taller than iPhone 4. When you add some UI controls to the lower part of the screen, it may need some tweaks to support both screen sizes.

59

Page 13: Introduction to “Life is short. Build stu Auto Layout ... · Obviously, we want the app to look good on both 3.5-inch & 4-inch iPhone, as well as, in both portrait & landscape orientation.

In the Interface Builder, drag a label from the Object Library and place it near the lower-right corner of the view. Double-click the label and change it to “Welcome to Auto Layout” or whatever title you want.

Figure 3-11. Adding a label to the view

If you have the preview opened in the Assistant Editor, you should see the UI update instantly (see figure 3-11). As you can see, without Auto Layout, the app is not able to display the label on a 3.5-inch device.

So how can you resolve this issue? Again, we need to setup a couple of constraints to make it work properly.

60

Page 14: Introduction to “Life is short. Build stu Auto Layout ... · Obviously, we want the app to look good on both 3.5-inch & 4-inch iPhone, as well as, in both portrait & landscape orientation.

First, we’ll add a constraint such that the label stays close to the bottom of the view. This time we’ll use the “Control-drag” approach to apply auto layout. I prefer this approach to the Auto Layout menu, but that’s just me. To add the constraint, hold the control key and drag from the label to the bottom of the superview. As you release the buttons, a pop-over menu appears showing a list of constraint options. Select “Bottom Space to Bottom Layout Guide” to set a vertical space constraint from the view controller's bottom layout guide to the label's bottom. This will pin the label a fixed distance to the bottom of the view. As soon as the constraint is added, Interface Builder displays constraint lines in both red and orange indicating there are some missing constraints.

To resolve the auto layout constraints, go to the Document Outline. Simply click the red arrow icon, followed by the red indicator and finally click “Add missing constraints”.

Figure 3-13. Adding missing constraints

61

Figure 3-12. Control-drag to add constraints

Page 15: Introduction to “Life is short. Build stu Auto Layout ... · Obviously, we want the app to look good on both 3.5-inch & 4-inch iPhone, as well as, in both portrait & landscape orientation.

When you preview the UI or run the app in simulator, the label should display properly on iPhone 3.5-inch and even in landscape mode.

Top and Bottom Layout GuideYou may wonder what the Bottom Layout Guide means. Generally, the Bottom Layout Guide refers to the bottom of the view, like the one shown in the example. However, the Bottom Layout Guide varies. Sometimes we embed a tab bar (we’ll discuss in later chapter) in the view controller, the Bottom Layout Guide will refer to the top of tab bar.

For the Top Layout Guide, it sits at 20 points (which is the height of the status bar) from the top of the view. Again the guide varies. If the view controller is embedded in a navigation controller, the guide sits below the navigation bar.

If you’re confused, the best way is to check out the guide in Interface Builder. Simply select the “Top Layout Guide” or “Bottom Layout Guide” in the Document Outline. Interface Builder will show you the guide line in light blue.

SummaryIn this chapter, we went through the basics of Auto Layout. Yes, it’s just the basics as I don’t want to scare you away from learning Auto Layout. As we dig deeper and create a real app, we’ll continue to explore some other features of Auto Layout. By now, I hope you should have some basic ideas about how to lay out your app UI and make it fit for all screen sizes.

62

Figure 3-14. Top layout guide

Page 16: Introduction to “Life is short. Build stu Auto Layout ... · Obviously, we want the app to look good on both 3.5-inch & 4-inch iPhone, as well as, in both portrait & landscape orientation.

Most of the beginners (and even some experienced iOS programmers) avoid using Auto Layout as it looks confusing. If you start to love Auto Layout after reading this chapter, you’re on your way to becoming a competent iOS developer. The original iPhone was launched in 2007. Over these years, there have been tons of changes and advancements in the area of iOS development. Unlike the good old days when your apps just needed to run on a 3.5-inch, non-retina device, your apps now have to cater to various screen resolution and sizes. This is why I devoted a whole chapter to Auto Layout.

So take some time to digest the materials.

For your reference, you can download the complete Xcode project from https://www.dropbox.com/s/4htvd6hvhlln9q5/HelloWorldAutoLayout.zip.

63