Home > Articles > Programming > General Programming/Other Languages

This chapter is from the book

3.3 Building the App’s UI

In this section, you’ll build the Tip Calculator UI using the techniques you learned in Chapter 2. Here, we’ll show the detailed steps for building the UI—in later chapters, we’ll focus on new UI features.

3.3.1 Creating the Project

As you did in Section 2.3, begin by creating a new Single View Application iOS project. Specify the following settings in the Choose options for your new project sheet:

  • Product Name: TipCalculator.
  • Organization Name: Deitel and Associates, Inc.—or you can use your own organization name.
  • Company Identifier: com.deitel—or you can use your own company identifier or use edu.self.
  • Language—Swift.
  • Devices: iPhone—This app is designed for iPhones and iPod touches. The app will run on iPads, but it will fill most of the screen and be centered, as in Fig. 3.7.

    Fig. 3.7

    Fig. 3.7 | Tip Calculator running in the iPad Air simulator.

After specifying the settings, click Next, indicate where you’d like to save your project and click Create to create the project.

Configuring the App to Support Only Portrait Orientation

In landscape orientation, the numeric keypad would obscure parts of the Tip Calculator’s UI. For this reason, this app will support only portrait orientation. In the project settings’ General tab that’s displayed in the Xcode Editor area, scroll to the Deployment Info section, then for Device Orientation ensure that only Portrait is selected. Recall from Section 2.5.1 that most iPhone apps should support portrait, landscape-left and landscape-right orientations, and most iPad apps should also support upside down orientation. You can learn more about Apple’s Human Interface Guidelines at:

http://bit.ly/HumanInterfaceGuidelines

3.3.2 Configuring the Size Classes for Designing a Portrait Orientation iPhone App

In Chapter 2, we designed a UI that supported both portrait and landscape orientations for any iOS device. For that purpose, we used the default size class Any for the design area’s width and height. In this section, you’ll configure the design area (also called the canvas) for a tall narrow device, such as an iPhone or iPod touch in portrait orientation. Select Main.storyboard to display the design area—also known as the canvas. At the bottom of the canvas, click the Size Classes control to display the size classes tool, then click in the lower-left corner to specify the size classes Compact Width and Regular Height (Fig. 3.8).

Fig. 3.8

Fig. 3.8 | Size classes tool with Compact Width and Regular Height selected.

3.3.3 Adding the UI Components

In this section, you’ll add and arrange the UI components to create the basic design. In Section 3.3.4, you’ll add auto layout constraints to complete the design.

Step 1: Adding the “Bill AmountLabel

First, you’ll add the “Bill AmountLabel to the UI:

  1. Drag a Label from the Object library to the scene’s upper-left corner, using the blue guide lines to position the Label at the recommended distance from the scene’s top and left (Fig. 3.9). The plus.jpg symbol indicates that you’re adding a new component to the UI.

    Fig. 3.9

    Fig. 3.9 | Adding the “Bill AmountLabel to the scene.

  2. Double click the Label, type Bill Amount, then press Enter to change its Text attribute.

Step 2: Adding the Label That Displays the Formatted User Input

Next, you’ll add the blue Label that displays the formatted user input:

  1. Drag another Label below the “Bill AmountLabel, such that the placement guides appear as shown in Fig. 3.10. This is where the user input will be displayed.

    Fig. 3.10

    Fig. 3.10 | Adding the Label in which the formatted user input will be displayed.

  2. Drag the middle sizing handle at the new Label’s right side until the blue guide line at the scene’s right side appears (Fig. 3.11).

    Fig. 3.11

    Fig. 3.11 | Resizing the Label where the formatted user input will be displayed.

  3. In the Attributes inspector, scroll to the View section and locate the Label’s Background attribute. Click the attribute’s value, then select Other... to display the Colors dialog. This dialog has five tabs at the top that allow you to select colors different ways. For this app, we used the Crayons tab. On the bottom row, select the Sky (blue) crayon as the color (Fig. 3.12), then set the Opacity to 50%—this allows the scene’s white background to blend with the Label’s color, resulting in a lighter blue color. The Label should now appear as shown in Fig. 3.13.

    Fig. 3.12

    Fig. 3.12 | Selecting the Sky crayon for the Label’s background color.

    Fig. 3.13

    Fig. 3.13 | Label with Sky blue background and 50% opacity.

  4. A Label’s default height is 21 points. We increased this Label’s height to add space above and below its text to make it more readable against the colored background. To do so, drag the bottom-center sizing handle down until the Label’s height is 30 (Fig. 3.14).

    Fig. 3.14

    Fig. 3.14 | Label with Sky blue background and 50% opacity.

  5. With the Label selected, delete the value for its Text property in the Attributes inspector. The Label should now be empty.

Step 3: Adding the “Custom Tip Percentage:Label and a Label to Display the Current Custom Tip Percentage

Next, you’ll add the Labels in the UI’s third row:

  1. Drag another Label onto the scene and position it below the blue Label as shown in Fig. 3.15.

    Fig. 3.15

    Fig. 3.15 | Adding the “Custom Tip Percentage:Label to the scene.

  2. Double click the Label and set its text to Custom Tip Percentage:.
  3. Drag another Label onto the scene and position it to the right of the “Custom Tip Percentage:Label (Fig. 3.16), then set its text to 18%—the initial custom tip percentage we chose in this app, which the app will update when the user moves the Slider’s thumb. The UI should now appear as shown in Fig. 3.17.

    Fig. 3.16

    Fig. 3.16 | Adding the Label that displays the current custom tip percentage.

    Fig. 3.17

    Fig. 3.17 | UI design so far.

Step 4: Creating the Custom Tip Percentage Slider

You’ll now create the Slider for selecting the custom tip percentage:

  1. Drag a Slider from the Object library onto the scene so that it’s the recommended distance from the “Custom Tip Percentage:Label, then size and position it as shown in Fig. 3.18.

    Fig. 3.18

    Fig. 3.18 | Creating and sizing the Slider.

  2. Use the Attributes inspector to set the Slider’s Minimum value to 0 (the default), Maximum value to 30 and Current value to 18.

Step 5: Adding the “15%” and “18%Labels

Next, you’ll add two more Labels containing the text 15% and 18% to serve as column headings for the calculation results. The app will update the “18%Label when the user moves the Slider’s thumb. Initially, you’ll position these Labels approximately—later you’ll position them more precisely. Perform the following steps:

  1. Drag another Label onto the scene and use the blue guides to position it the recommended distance below the Slider (Fig. 3.19), then set its Text to 15% and its Alignment to centered.

    Fig. 3.19

    Fig. 3.19 | Adding the Label and right aligning it with the blue Label.

  2. Next you’ll duplicate the “15%Label, which copies all of its settings. Hold the option key and drag the “15%Label to the right (Fig. 3.20). You can also duplicate a UI component by selecting it and typing cmd.jpg + D, then moving the copy. Change the new Label’s text to 18%.

    Fig. 3.20

    Fig. 3.20 | Duplicating the “15%Label so that you can create the “18%Label.

Step 6: Creating the Labels That Display the Tips and Totals

Next, you’ll add four Labels in which the app will display the calculation results:

  1. Drag a Label onto the UI until the blue guides appear as in Fig. 3.21.

    Fig. 3.21

    Fig. 3.21 | Creating the first yellow Label.

  2. Drag the Label’s bottom-center sizing handle until the Label’s Height is 30, and drag its left-center sizing handle until the Label’s Width is 156.
  3. Use the Attributes inspector to clear the Text attribute, set the Alignment so the text is centered and set the Background color to Banana, which is located in the Color dialog’s Crayons tab in the second row from the bottom.
  4. Set the Autoshrink property to Minimum Font Scale and change the value to .75—if the text becomes too wide to fit in the Label, this will allow the text to shrink to 75% of its original font size to accommodate more text. If you’d like the text to be able to shrink even more, you can choose a smaller value.
  5. Next duplicate the yellow Label by holding the option key and dragging the Label to the left to create another Label below the “15%Label.
  6. Select both yellow Labels by holding the Shift key and clicking each Label. Hold the option key and drag any one of the selected Labels down until the blue guides appear as shown in Fig. 3.22.

    Fig. 3.22

    Fig. 3.22 | Creating the second row of yellow Labels.

  7. Now you can center the “15%” and “18%Labels over their columns. Drag the “TipLabel so that the blue guide lines appear as shown in Fig. 3.23. Repeat this for the “18%Label to center it over the right column of yellow Labels.

    Fig. 3.23

    Fig. 3.23 | Repositioning the “15%Label.

Step 7: Creating the “Tip” and “TotalLabels to the Left of the Yellow Labels

Next you’ll create the “Tip” and “TotalLabels:

  1. Drag a Label onto the scene, change its Text to Total, set its Alignment to right aligned and position it to the left of the second row of yellow Labels as in Fig. 3.24.

    Fig. 3.24

    Fig. 3.24 | Positioning the “TotalLabel.

  2. Hold the option key and drag the “TotalLabel up until the blue guides appear as shown in Fig. 3.25. Change the new Label’s text to Tip, then drag it to the right so that the right edges of the “Tip” and “TotalLabels align.

    Fig. 3.25

    Fig. 3.25 | Duplicating the “TotalLabel so that you can create the “TipLabel.

Step 8: Creating the Text Field for Receiving User Input

You’ll now create the Text Field that will receive the user input. Drag a Text Field from the Object library to the bottom edge of the scene, then use the Attributes inspector to set its Keyboard Type attribute to Number Pad and its Appearance to Dark. This Text Field will be hidden behind the numeric keypad when the app first loads. You’ll receive the user’s input through this Text Field, then format and display it in the blue Label at the top of the scene.

3.3.4 Adding the Auto Layout Constraints

You’ve now completed the Tip Calculator app’s basic UI design, but have not yet added any auto layout constraints. If you run the app in the simulator or on a device, however, you’ll notice that—depending on which simulator you use—some of the UI components extend beyond the trailing edge (Fig. 3.26). In this section, you’ll add auto layout constraints so that the UI components can adjust to display properly on devices of various sizes and resolutions.

Fig. 3.26

Fig. 3.26 | App in the iPhone 5s simulator without auto layout constraints added to the UI—some components flow off the trailing edge (the right side in this screen capture).

In Chapter 2, you manually added the required auto layout constraints. In this section, you’ll use Interface Builder to add missing constraints automatically, then run the app again to see the results. You’ll then create some additional constraints so that the app displays correctly in the simulator or on a device.

Step 1: Adding the Missing Auto Layout Constraints

To add the missing auto layout constraints:

  1. Click the white background in the design area or select View in the document outline window.
  2. At the bottom of the canvas, click the Resolve Auto Layout Issues (icon-1.jpg) button and under All Views in View Controller select Add Missing Constraints.

Interface Builder analyzes the UI components in the design and based on their sizes, locations and alignment, then creates a set of auto layout constraints for you. In some cases, these constraints will be enough for your design, but you’ll often need to tweak the results. Figure 3.27 shows the UI in the iPhone 5s simulator after Interface Builder adds the missing constraints. Now, all of the UI components are completely visible, but some of them are not sized and positioned correctly. In particular, the yellow Labels should all be the same width.

Fig. 3.27

Fig. 3.27 | App in the simulator after Interface Builder adds the missing auto layout constraints—some components are not sized and positioned correctly.

Step 2: Setting the Yellow Labels to Have Equal Widths

To set the yellow Labels to have equal widths:

  1. Select all four yellow Labels by holding the shift key and clicking each one.
  2. In the auto layout tools at the bottom of the canvas, click the Pin tools icon (icon-1.jpg). Ensure that Equal Widths is checked and click the Add 3 Constraints button, as shown in Fig. 3.28. Only three constraints are added, because three of the Labels will be set to have the same width as the fourth.

    Fig. 3.28

    Fig. 3.28 | Setting Equal Widths for the yellow Labels.

Figure 3.29 shows the UI in the simulator. Setting the yellow Labels to Equal Widths caused the 18% Label over the right column to disappear and the “Tip” and “TotalLabels to become too narrow to display.

Fig. 3.29

Fig. 3.29 | App in the simulator after setting the yellow Labels to equal widths.

Step 3: Debugging the Missing “18%Label

Based on the initial design, the missing “18%Label should be centered over the right column of yellow Labels. If you select that Label in the canvas and select the Size inspector in the Utilities area, you can see the missing Label’s complete set of constraints (Fig. 3.30).

Fig. 3.30

Fig. 3.30 | “18%Label’s constraints.

There are two constraints on the “18%Label’s horizontal positioning:

  • The Trailing Space to: Superview constraint specifies that this Label should be 60 points from the scene’s trailing edge.
  • The Align Center X to: Label constraint specifies that this Label should be centered horizontally over the specified Label.

These two constraints conflict with one another—depending on the yellow Label’s width, the “18%Label could appear different distances from the scene’s trailing edge. By removing the Trailing Space to: Superview constraint, we can eliminate the conflict. To do so, simply click that constraint in the Size inspector and press the delete key. Figure 3.31 shows the final UI in the iPhone 5s simulator, but you can test the UI in other simulators to confirm that it works correctly in each.

Fig. 3.31

Fig. 3.31 | App with its final UI running in the simulator.

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