Devices and Auto Layout - Introducing iOS 8 (2015)

Introducing iOS 8 (2015)

Chapter 7. Devices and Auto Layout

In this chapter, you will learn how to design an app with an interface for multiple devices. You will be introduced to all of Apple’s devices and device sizes. This chapter will give you a foundation in app design so that you can start designing the user interface for your own apps.

Screen Sizes

iOS runs on many different device sizes and formats, including iPhone, iPod Touch, iPad, and iPad Mini. Table 7-1 contains all of these devices and their size in pixels.

Table 7-1. Device sizes

Device

Height (px)

Width (px)

iPhone

480

320

iPhone 4 (Retina)

960

640

iPhone 5 (Retina)

1136

640

iPhone 6 (Retina)

1334

750

iPhone 6 Plus (Retina HD)

1920

1080

iPad

1024

768

iPad w/ Retina

2048

1536

iPad Mini

1024

768

iPad Mini w/ Retina

2048

1536

Retina Displays

Pixels represent the drawable units on a display, just like the boxes on a sheet of graph paper. As devices have evolved, more and more pixels have been added. This creates a more dense area of pixels, providing more detail for each square inch of the device. This pixel-per-inch (PPI) is the standard for measuring the density of a display. When Steve Jobs announced the iPhone 4, he claimed the human eye could not notice the difference above a 300 PPI display. The iPhone 4 boasted a 326 PPI, and the term Retina has been used to describe any PPI over 300. The iPhone 6 Plus boasts a 401 PPI Retina HD display.

To help manage the Retina and Retina HD images for your application, Apple has provided some filenaming keywords:

Image.png

Standard-sized image for non-Retina displays

Image@2x.png

Double-sized image for Retina displays

Image@3x.png

Triple-sized image for Retina HD displays

If you use the @2x and @3x keywords, Xcode will automatically use your Retina or Retina HD images when needed.

Swift requires iOS 7 or newer. iOS 7 requires an iPhone 4 or newer. Since all phones from the iPhone 4 and newer have a Retina display, it is guaranteed that all iPhone-sized devices will have a Retina display or better. However, some iPads also run iOS 7, but are not guaranteed to have a Retina display. The iPad Mini and iPad 2 both run iOS 7 and have the same non-Retina display. This 1024 x 768 px display is the only non-Retina display you will need to consider when designing your app.

Orientation

There are many devices for iOS, and there are four orientations for each device. A device can be positioned in one of four possible orientations at a time:

Portrait

Device is positioned so that the sides are longer vertically than horizontally and the home button is at the bottom of the device. This is the default orientation.

Portrait Upside Down

Device is positioned so that the sides are longer vertically than horizontally and the home button is at the top of the device.

Landscape Left

Device is positioned so that the top and bottom are longer horizontally than vertically and the home button is on the left of the device.

Landscape Right

Device is positioned so that the top and bottom are longer horizontally than vertically and the home button is on the right of the device.

Each application must specify its supported orientations. A supported orientation is an orientation in which the application will update or adjust depending on the position of the device. By default, Portrait, Landscape Left, and Landscape Right are all enabled as supported orientations.

Universal Apps

Apps must adjust depending on the device. Apple provides three different formats to help support these adjustments.

The first format is an iPhone app. An iPhone app will run as designed on an iPhone or iPod Touch. However, an iPhone app can also be run on an iPad. Because the iPad has more pixels than an iPhone, the iPad will display the iPhone app in scaled mode. Scaled mode shows the app in an iPhone-sized window on the iPad. Scaled mode also offers the ability to scale up the iPhone app to fill the entire iPad display. However, this requires the iPhone design to be stretched and creates a low-resolution, or pixelated, effect.

The second format of app is an iPad app. An iPad app will only run on an iPad or iPad Mini. An iPad app cannot be run on an iPhone or iPod Touch. The iPad app is designed specifically for iPad and will not scale or stretch.

Finally, the third format is universal. A universal app is designed to run on any device: iPhone, iPod Touch, iPad, or iPad Mini. A universal app contains a specific interface for both iPhone- and iPad-sized devices. To help developers ensure their design works well on all device sizes, Apple created Auto Layout.

Auto Layout

Auto Layout is a set of tools used to size and position elements on the screen. A traditional system uses fixed coordinates and sizes, but Auto Layout uses rules to size and position elements. These rules are called constraints.

Constraints are rules for size or positioning, for example the left side of the Label should be offset 20 pts from the left edge of the containing view. This constraint-based system allows the elements on the interface to resize for any size display.

To place a Label in the bottom-right corner of an iPhone 5, a traditional system would set the Y-offset to 550, the X-offset to 250, the width to 50, and the height to 10 (Figure 7-1).

Traditional Label in bottom-right corner of screen in Portrait

Figure 7-1. Traditional Label in bottom-right corner of screen in Portrait

This system works well until another display size or orientation is brought into consideration. If the display is rotated to Landscape Left, a traditional system will not change the coordinates of the Label, leaving it off the screen (Figure 7-2).

Traditional Label after Landscape Left rotate

Figure 7-2. Traditional Label after Landscape Left rotate

If Auto Layout is used to position a Label in the bottom-right corner, it appears and acts the same in portrait or landscape (Figure 7-3).

Label in bottom right with Portrait Auto Layout

Figure 7-3. Label in bottom right with Portrait Auto Layout

Since Auto Layout uses constraints based on surrounding elements and edges, when the device is rotated into Landscape Left, the Label updates accordingly (Figure 7-4).

Label in bottom right with Landscape Auto Layout

Figure 7-4. Label in bottom right with Landscape Auto Layout

Attributes

Constraints can be created based on a variety of different attributes. For example, you might want to position the right edge of a label 30 pts from the edge of the containing view (Figure 7-5). The containing view is the encapsulating view holding the elements together. Instead of positioning the right edge of an element, you can position many other attributes of an element.

Storyboard with Label positioned via Auto Layout

Figure 7-5. Storyboard with Label positioned via Auto Layout

The left, right, top, and bottom edges are common positioning attributes. For example, the English language reads from left to right. However, if the language you are presenting does not read left to right, like Arabic, the spacing should be flipped. In addition to the left and right attributes, Apple created the leading and trailing attributes. These attributes act as the left and right edges in a left-to-right language. They also act as the right and left edges in a right-to-left language.

Constraints can also be created based on the width, height, centerX, and centerY attributes. The width and height attributes are typically used to fix or set equal sizing across multiple elements. For example, you might have four buttons in a row across the bottom of the display. As the screen gets wider, the buttons should all grow to the same size.

The centerX and centerY attributes are used to position elements from the horizontal center or vertical center of an element. Finally, the baseline attribute is only available on elements with text. The baseline refers to the bottom boundary for a line of text.

Values

Each constraint must be set to a value. The value can be a specific number, a range of values, or the Standard Value. For example, on an iPhone, the Standard Value may be 20 pts, but for iPad, the Standard Value may be 25 pts. These values are set by Apple and vary based on device and orientation. Constraints can also be set to a specific number, for example, a constraint that offsets the leading edge of a Label by 30 pts. Auto Layout also supports ranges or inequalities as well. For example, consider a constraint setting the leading offset to be greater than or equal to 20 pts. This allows the leading offset to expand or lock as the container view changes. Finally, the Standard Value is the default spacing for that particular device.

Intrinsic Size

In some cases, it is necessary to allow an element to size itself. For example, a Label with a fixed width may clearly display the text “Tap here to enter.” However, when the text is translated to German, “Tippen Sie hier, um geben,” it is wider than its English translation. The fixed width of the Label will truncate the German text.

To avoid this issue, typically seen in Labels, Auto Layout has an Intrinsic Content Size option. This option provides organic sizing of the element based on the content. To enable this option, select a Label on the interface, select Editor from the top menu bar, and then click “Size to Fit Content.”

Priority

In most cases, there will be many constraints for a given view. The elements on the screen will move relative to their size and constraints. In some cases, constraints can conflict with each other. A priority level is specified for each constraint to decide which constraint will take precedent.

Creating Constraints

Constraints are created inside of the storyboard file. When an element is dragged from the Object Library onto the interface, it is unconstrained. If the application is run without constraints, Xcode will pin the element to its absolute position. This means that if the containing view is resized, the elements will not move. To make the elements adjust to the change in size, constraints must be created. Each element should have a vertical and horizontal constraint. There are many ways to create constraints for your elements.

The Control-Drag Method

The most convenient way to create a constraint is to Control-drag between two elements. Select the element on the interface, hold Control, and drag the mouse from the element toward a neighboring element or edge. A small pop-up menu will be shown (Figure 7-6). Depending on the direction you drag, different options will be displayed.

Pop-up constraint menu

Figure 7-6. Pop-up constraint menu

If the drag is to the right, an option for the Trailing Space Constraint will be shown. If the drag is to the left, an option for the Leading Space Constraint will be shown. A left or right drag will also provide an option to align the element to the vertical center. A drag to the top will provide an option for the Top Space Constraint, and a drag to the bottom will provide an option for the Bottom Space Constraint. Finally, a top or bottom drag will also provide an option to align the element to the Horizontal Center.

Auto Layout Buttons

Constraints can also be created via the Auto Layout menu in the bottom-right corner of the Storyboard Editor (Figure 7-7). The Auto Layout menu is a group of four buttons used to help size and position elements using Auto Layout.

Auto Layout menu

Figure 7-7. Auto Layout menu

The Align button

The first button from the left is the Align button. This button provides the ability to create alignment-based constraints, such as centering a view or aligning the edges of neighboring views.

To use the Align button, select an element and then click the first button in the bottom-left of your screen. The Align menu will appear and show a list of possible new constraints (Figure 7-8). Check the box next to the new constraint and enter the offset value in the text box on the right side. The text box also provides a drop-down menu with the Canvas and Standard Value options. The Canvas option will calculate the offset using the current position on the interface. The Standard Value will be determined by Apple’s best practices and change depending on the device size. To complete the constraint, click Add Constraints.

Align button menu

Figure 7-8. Align button menu

The Pin button

The next button is the Pin button. The Pin button creates constraints by defining spacing to the nearest neighbor or specifying a width or height. The Pin button has a few different sections from top to bottom.

The topmost section is used to create a new constraint based on a specific offset from the top, right, bottom, or left side of the selected element. The four input boxes receive the value, and a new constraint is created for each side of the element. The Pin menu can be tricky; the constraints will not be created unless the corresponding red line between the square and the input box is bolded (Figure 7-9). Once this red line is clicked, it will become bolded and the bottom of the menu will update with Add 1 Constraint.

Pin menu

Figure 7-9. Pin menu

The second section from the top is used to set a fixed width or height to the element. Be careful when using fixed widths or heights, especially with Labels. The fixed width can result in the Label’s text being truncated unexpectedly.

The third section from the top is used to set equal widths or heights across many elements, and the aspect ratio constraint will ensure the height and width aspect ratio is not changed if the element is resized.

The Align and Pin menus have an Update Frames option as well. This option will move the affected elements to their new positions according to the updated constraints. The update can be executed for all the elements in the container or just the elements affected by the new constraints.

Finally, the Align option inside the Pin menu is one of the most powerful and helpful ways to create constraints. With two elements selected, the Align option will provide a list of attributes to align between two elements. This is very helpful to ensure a set of left-aligned Labels are all stacked evenly on top of each other.

The Resolve Auto Layout Issues button

The third button is the Resolve Auto Layout Issues button. This button helps fix Auto Layout issues by providing suggestions and resetting constraints. It can analyze the view and create constraints based on the layout of the interface elements.

The Issues menu is divided into two menus, top and bottom (Figure 7-10). The top half only affects the selected element on the screen, while the bottom half affects all elements. The most helpful feature of the Issues menu is the “Reset to Suggested Constraints” option. This option will remove all the current constraints and create new constraints based on where the elements are positioned on the interface. This option serves as a great starting point, since the constraints can be edited after they are created.

Issues menu

Figure 7-10. Issues menu

The Resizing Behavior button

The last button is the Resizing Behavior button. This button provides a menu to control how constraints are applied when resizing takes place (Figure 7-11). Depending on how many elements are selected, options in each menu may be disabled. For example, the equal widths option sets a group of elements to the same width. However, this option will not be enabled if only one element is selected.

Resizing Behavior menu

Figure 7-11. Resizing Behavior menu

The Guidelines Method

When an element is positioned on the interface, guidelines are shown at the horizontal center, vertical center, and toward the edges of the interface (Figure 7-12). Using these guidelines can help Xcode to suggest and automatically create constraints for you.

Guidelines

Figure 7-12. Guidelines

To automatically create constraints, position an element on the interface while using one of the guidelines. Then click the Resolve Auto Layout Issues button; it features a triangle with wings. Once the Resolve Auto Layout Issues button is clicked, a small menu will appear. Scroll to the top and select “Reset to Suggested Constraints” (Figure 7-13). This option will tell Xcode to remove any existing constraints and create constraints based on the element’s current positioning. Open the Document Outline to view all the constraints for the interface.

Element on guideline

Figure 7-13. Element on guideline

Testing Layout Constraints

When positioning an element with Auto Layout, the constraints will change colors to provide feedback. If the constraints shown are orange, that means there are not enough constraints provided to properly position the element, or there is an error (Figure 7-14).

Orange constraints

Figure 7-14. Orange constraints

The Document Outline shows a yellow triangle or red circle icon when there is an Auto Layout issue. Clicking on the Auto Layout error icon will show a list of the current Auto Layout issues. Each issue will be listed, and a reason will be provided; next to each issue will be a yellow triangle, a warning, or a red circle, for an error (Figure 7-15).

Constraint errors and warnings

Figure 7-15. Constraint errors and warnings

Click on the icon next to the issue, and a Fix-It pop-up box will be shown (Figure 7-16). This pop-up box will present a suggested solution for the issue. Click the Fix button to automatically add the fix. Be sure to investigate the constraints added to your view via the Fix-It system, since sometimes they do not work for each device.

Constraint Fix-It

Figure 7-16. Constraint Fix-It

Previewing

It’s important to test your interface in multiple device sizes and shapes. Xcode has a built in Previewer, which will show exactly how the interface will look on different devices (Figure 7-17). To show the Previewer, first hide the Inspector. Then show the Assistant Editor. Once the Assistant Editor is shown, click the word Automatic on the top toolbar of the Assistant Editor. A drop-down menu will appear; select Preview. The right side of your screen will now show a preview of the interface on a device. To add more devices, click the small plus icon in the bottom left of the Assistant Editor window.

Previewer

Figure 7-17. Previewer

Exercise: Building More on the Passport App

This exercise builds on top of the Passport app from Chapters 5 and 6. In this exercise, Passport will be updated to work with Auto Layout. The user interface will adjust to an iPhone or iPad in Landscape or Portrait orientation (Figure 7-18).

Finished exercise screenshot

Figure 7-18. Finished exercise screenshot

Open the Passport project file inside Xcode. Click Passport in the Project Navigator, and the project details will appear. Scroll down and set Devices to Universal. Then check the Upside Down, Landscape Left, and Landscape Right boxes. Then open Images.xcassets and highlight AppIcon. Press Delete. Right-click in the white sidebar and select New App Icon. A new iPad and iPhone App Icon grid will appear. Open the Passport Icon folder and drag in the corresponding icons.

On the toolbar, click the iOS Simulator drop-down menu next to Passport.

The drop-down menu lists all the devices available in the iOS Simulator (Figure 7-19). Select iPad Air and click Play. The iOS Simulator will now launch in the form of an iPad Air.

Drop-down devices

Figure 7-19. Drop-down devices

The iPad Air simulator is very large, especially on a small screen. To adjust this, go to the top menu bar and select Window→Scale→50% (Figure 7-20). The iPad Air simulator will now operate at half the standard size.

iPad Air drop-down menu

Figure 7-20. iPad Air drop-down menu

The Passport app does not look very pleasing on the iPad. The image has been moved, and the labels are offset (Figure 7-21). This is because the current positioning system works with fixed width and height coordinates.

iPad Air simulator

Figure 7-21. iPad Air simulator

You will need to change the positioning system to Auto Layout. Open the Main.storyboard file and then select the File Inspector (Figure 7-22). Check the box Use Auto Layout and then Use Size Classes. Then click Enable Size Classes (Figure 7-23).

File Inspector

Figure 7-22. File Inspector

Enable Size Classes button

Figure 7-23. Enable Size Classes button

Size classes can be used to change layouts for different device sizes. The positioning system is now set to Auto Layout. To take advantage of Auto Layout, constraints must be added to each interface. Open the Passport Scene.

Position the Image View along the horizontal-center guideline. Then drag the Image View up to the top buffer guideline. Click the Align button and select Horizontal Center in Container; then Add 1 Constraint. Next, select the Pin button and from the top drop-down menu, select Use Standard Value. Then check the Width and Height options and click Add 3 Constraints (Figure 7-24).

Repositioned Image View

Figure 7-24. Repositioned Image View

Drag the three right-side Labels under the bottom-right corner of the Image View. Next, draw a box and select the right-side Labels along with the Image View. Click the Align button and check the Trailing Edges option. Then click Add Constraints. With just the right-side Labels selected, click the Pin button and select Use Standard Value from the top drop-down menu. Then from the Update Frames drop-down, select Items of New Constraints and click Add Constraints (Figure 7-25).

Repositioned right-side Labels

Figure 7-25. Repositioned right-side Labels

Drag the three left-side labels under the bottom-left corner of the Image View. Next, draw a box and select the left-side Labels along with the Image View. Click the Align button and check the Leading Edges option. Then click Add Constraints. With just the left-side Labels selected, click the Pin button and select Use Standard Value from the top drop-down menu. Then from the Update Frames drop-down, select Items of New Constraints and click Add Constraints (Figure 7-26).

Repositioned left-side Labels

Figure 7-26. Repositioned left-side Labels

Position the button along the horizontal center guideline. Then drag it up until it is placed just below the bottom Label’s base guideline. Click the Align button and select Horizontal Center in Container and then Add 1 Constraint. Finally, click the Pin button and select Use Current Canvas Value from the top drop-down menu; then Add Constraint (Figure 7-27).

Repositioned button

Figure 7-27. Repositioned button

These constraints will be used and inherited on all size classes and layouts. Now tweak and modify these constraints for a specific size class. Click “Any, Any” at the bottom of the screen. A small grid will appear; this controls which size class is currently being edited. Click the bottom right of the grid (Figure 7-28). This size class is used for iPads in Portrait or Landscape orientation.

Regular, Regular size class

Figure 7-28. Regular, Regular size class

Select the Image View, and a blue vertical line will appear on the right side of the Image View. This is the height constraint for the Image View. Double-click this constraint and change its value from 225 to 400. Next, double-click the horizontal line below the Image View; this is the width constraint. Change the width constraint’s value from 225 to 400. The Image View will resize, and the Labels and Buttons will reposition themselves (Figure 7-29).

Resized Image View

Figure 7-29. Resized Image View

To review these new constraints, use the Previewer. Before you open the Previewer, it is best to clear up some space; hide the Project Navigator and Inspector. Then open the Assistant Editor; its icon has two connected circles inside it. From the Assistant Editor toolbar, click Automatic. A drop-down menu will appear; select Preview→ Main.storyboard (Preview) (Figure 7-30).

Preview menu

Figure 7-30. Preview menu

The right side of the Xcode screen will now show a live preview of the interface on a 4-inch iPhone. Click the plus button in the bottom-left corner and then iPad. An iPad preview will be added to the right side of the Previewer (Figure 7-31). The interface looks much better on the iPad. Rotate the preview by clicking the small arrow at the bottom of the iPad preview. Notice the interface rotates, and the elements are still positioned properly. Rotate the iPhone 4-inch preview. The elements on the screen are being cut off and are not properly displayed.

Previewer

Figure 7-31. Previewer

Select the “Regular, Regular” link at the bottom of the screen and click the middle box in the top row of the grid. This will change the size class to “Any, Compact” (Figure 7-32). This size class is specifically for iPhones in Landscape. The interface will rotate, and some elements may be missing. To fix this, from the top menu bar, select Edit→Select All. All of the elements on the interface will be highlighted. Drag the Image View toward the top of the interface to reveal the missing elements.

“Any, Compact” size class

Figure 7-32. “Any, Compact” size class

This size class will require a completely new layout (Figure 7-33). Next, click the Resolve Auto Layout Issues button and then select Clear Constraints from the bottom of the menu; this will clear the current constraints only for this size class. Next, drag the Image View to the left-side guideline and then drag it up the top buffer guideline. With the Image View selected, click the Pin button and select Use Standard Value from the top drop-down menu and then select Use Current Canvas Value from the left drop-down menu. Then check the width and height checkboxes and select Add Constraints. Drag the Labels and Buttons and place them against the top buffer guideline; then drag them to the left until they touch the Image View’s right buffer guideline. Finally, click the Pin button and select Use Standard Value from the top drop-down menu, and then select Use Current Canvas Value from the left drop-down menu. Then click Add Constraints.

New layout

Figure 7-33. New layout

The app is now ready for testing; select iPhone 5s from the iOS Simulator drop-down menu and click the Play button. Rotate the simulator by selecting Hardware→Rotate Right from the top menu bar (Figure 7-34). Test the app with an iPad Air as well (Figure 7-35).

iPhone 5s Landscape screenshot

Figure 7-34. iPhone 5s Landscape screenshot

iPad Air screenshot

Figure 7-35. iPad Air screenshot

Don’t worry if you received an error, a warning, or your app did not run as expected. The best way to learn is to make mistakes. Practice makes perfect. A sample version of the project is available on AppSchool.com/book. Download it, compare it, and try, try again. Don’t be afraid to start the exercise over and walk through it until you get it right.