Home > Articles > Home & Office Computing > Entertainment/Gaming/Gadgets

This chapter is from the book

Using the View-Based Application Template

The easiest way to see how Xcode and Interface Builder manage to separate logic from display is to build an application that follows this approach. Apple has included a useful application template in Xcode that quickly sets up an empty view and an associated view controller. This View-Based Application template will be the starting point for many of your projects, so we'll spend the rest of this chapter getting accustomed to using it.

Implementation Overview

The project we'll be building is simple: Instead of just writing the typical "Hello World" app, we want to be a bit more flexible. The program will present the user with a field (UITextField) for typing and a button (UIButton). When the user types into the field and presses the button, the display will update an onscreen label (UILabel) so that "Hello" is seen, followed by the user's input. The completed HelloNoun, as we've chosen to call this project, is shown in Figure 6.3.

Figure 6.3

Figure 6.3 The app will accept input and update the display based on what the user types.

Although this won't be a masterpiece of development, it does contain almost all the different elements we discuss in this hour: a view, a controller, outlets, and actions. Because this is the first full development cycle that we've worked through, we'll pay close attention to how all the pieces come together and why things work the way they do.

Setting Up the Project

First we want to create the project, which we'll call HelloNoun, in Xcode:

  1. Launch Xcode from the Developer/Applications folder.
  2. Choose File, New Project.
  3. You'll be prompted to choose a project type and a template. On the left side of the New Project window, make sure that Application is selected under the iPhone OS project type. Next find and select the View-Based Application option from the list on the right, as shown in Figure 6.4, and then click Choose.
    Figure 6.4

    Figure 6.4 Choose the View-Based Application template.

This will create a simple application structure consisting of an application delegate, a window, a view, and a view controller. After a few seconds, your project window will open (see Figure 6.5).

Figure 6.5

Figure 6.5 Your new project is open and ready for coding.

Classes

Click the Classes folder and review the contents. You should see four files (visible in Figure 6.5). The HelloNounAppDelegate.h and HelloNounAppDelegate.m files make up the delegate for the instance of UIApplication that our project will create. In other words, these files can be edited to include methods that govern how the application behaves when it is running. By default, the delegate will be responsible for one thing: adding a view to a window and making that window visible. This occurs in the aptly named applicationDidFinishLaunching method in HelloNounAppDelegate.m:

 - (void)applicationDidFinishLaunching:(UIApplication *)application {
     // Override point for customization after app launch
     [window addSubview:viewController.view];
     [window makeKeyAndVisible];
 }

You won't need to edit anything in the application delegate, but keep in mind the role that it plays in the overall application life cycle.

The second set of files, HelloNounViewController.h and HelloNounViewController.m, will implement the class that contains the logic for controlling our view—a view controller (UIViewController). These files are largely empty to begin, with just a basic structure in place to ensure that we can build and run the project from the outset. In fact, feel free to click the Build and Run button at the top of the window. The application will compile and launch, but there won't be anything to do!

To impart some functionality to our app, we need to work on the two areas we discussed previously: the view and the view controller.

XIB Files

After looking through the classes, click the Resources folder to show the XIB files that are part of the template. You should see MainWindow.xib and HelloNounViewController.xib files. Recall that these files are used to hold instances of objects that we can add visually to a project. These objects are automatically instantiated when the XIB loads. Open the MainWindow.xib file by double-clicking it in Xcode. Interface Builder should launch and load the file. Within Interface Builder, choose Window, Document to show the components of the file.

The MainWindow XIB, shown in Figure 6.6, contains icons for the File's Owner (UIApplication), the First Responder (an instance of UIResponder), the HelloNoun App Delegate (HelloNounAppDelegate), the Hello Noun View Controller (HelloNounViewController), and our application's Window (UIWindow).

Figure 6.6

Figure 6.6 The MainWindow.xib file handles creating the application's window and instantiating our view controller.

As a result, when the application launches, MainWindow XIB is loaded, a window is created, along with an instance of the HelloNounViewController class. In turn, the HelloNounViewController defines its view within the second XIB file, HelloNounViewController.xib—this is where we'll visually build our interface.

Any reasonable person is probably scratching his head right now wondering a few things. First, why does MainWindow.xib get loaded at all? Where is the code to tell the application to do this?

The MainWindow.xib file is defined in the HelloNoun-Info.plist file as the Main NIB File Base Name property value. You can see this yourself by clicking the Resources folder and then clicking the plist file to show the contents (see Figure 6.7).

Figure 6.7

Figure 6.7 The project's plist file defines the XIB loaded when the application starts.

Second, what about the HelloNounViewController.xib tells the application that it contains the view we want to use for our user interface? The answer lies in the MainWindow XIB file. Return to the MainWindow.xib document window in Interface Builder.

Click once on Hello Noun View Controller to select it in the list, and then press Command+1 or choose Attributes Inspector from the Tools menu. A small window will appear, as shown in Figure 6.8. Expand the View Controller section and you should see that the NIB Name field is set to HelloNounViewController. This means that the view controller loads its view from that XIB file.

Figure 6.8

Figure 6.8 After the MainWindow.xib instantiates the view controller, it loads its view from HelloNounViewController.xib.

In short, the application is configured to load MainWindow.xib, which creates an instance of our view controller class (HelloNounViewController), which subsequently loads its view from the HelloNounViewController.xib. If that still doesn't make sense, don't fret; we'll guide you through this every step of the way.

Preparing the View Controller Outlets and Actions

A view is connected to its view controller class through outlets and actions. These must be present in our code files before Interface Builder will have a clue where to connect our user interface elements, so let's work through adding those connection points now.

For this simple project, we're going to need to interact with three different objects:

  • A label (UILabel)
  • A text field (UITextField)
  • A button (UIButton)

The first two provide an output area and an input area for the user. The third triggers an action in our code to set the contents of the label to the contents of the text field. Based on what we now know, we can define the following outlets:

IBOutlet UILabel *userOutput;
IBOutlet UITextField *userInput;

And this action:

-(IBAction)setOutput:(id)sender;

Open the HelloNounViewController.h file in Xcode and add the IBOutlet and IBAction lines. Remember that the outlet directives fall inside the @interface block, and the action should be added immediately following it. Your header file should now resemble this:

#import <UIKit/UIKit.h>

@interface HelloNounViewController : UIViewController {
    IBOutlet UILabel *userOutput;
    IBOutlet UITextField *userInput;
}

-(IBAction)setOutput:(id)sender;

@end

Congratulations! You've just built the connection points that you'll need for Interface Builder to connect to your code. Save the file and get ready to create a user interface!

Creating the View

Interface Builder makes designing a user interface (UI) as much fun as playing around in your favorite graphics application. That said, our emphasis will be on the fundamentals of the development process and the objects we have at our disposal. Where it isn't critical, we move quickly through the interface creation.

Adding the Objects

The interface for our HelloNoun application is quite simple—it must provide a space for output, a field for input, and a button to set the output to the same thing as the input. Follow these steps to create the UI:

  1. Open HelloNounViewController.xib by double-clicking it within the Xcode Resources folder.
  2. If it isn't already running, Interface Builder will launch and open the XIB file, displaying the document window for the XIB file (see Figure 6.9). If you don't see the window, choose Window, Document from the menu.
    Figure 6.9

    Figure 6.9 The HelloNounViewController.xib file's view will contain all of the UI objects for the application.

  3. Double-click the icon for the instance of the view (UIView). The view itself, currently empty, will display. Open the Library by choosing Tools, Library. Make sure that the Objects button is selected within the Library—this displays all the components that we can drag into the view. Your workspace should now resemble Figure 6.10.
    Figure 6.10

    Figure 6.10 Open the view and the object Library to begin creating the interface.

  4. Add two labels to the view by clicking and dragging the label (UILabel) object from the Library into the view.
  5. The first label will simply be static text that says Hello. Double-click the default text that reads Label to edit it and change the content to read Hello. Position the second label underneath it; this will act as the output area.

    For this example, I changed the text of the second label to read <Noun Goes Here!>. This will serve as a default value until the user provides a new string. You may need to expand the text labels by clicking and dragging their handles to create enough room for them to display.

    I also chose to set my labels to align their text in the center. If you want to do the same, select the label within the view by clicking it, and then press Command+1 or choose Tools, Attributes Inspector from the menu. This opens the Attributes Inspector for the label, as demonstrated in Figure 6.11.

    Figure 6.11

    Figure 6.11 Use the Attributes Inspector to set the label to align in the middle.

    The Alignment setting within the layout section will give you the option of aligning to the center. You may also explore the other attributes to see the effect on the text, such as size, color, and so on. Your view should now resemble Figure 6.12.

    Figure 6.12

    Figure 6.12 Add two labels, one static, one to use for output, into the view.

  6. Once you're happy with the results, it's time to add the elements that the user will be interacting with: the text field and button. For the field, find the Text Field object (UITextField) within the Library and click and drag it under your two labels. Using the handles on the label, stretch it so that it matches the length of your output label.
  7. Click-drag a Round Rect button (UIButton) from the Library into the view, positioning it right below the text field. Double-click in the center of the button to add a title to the button, such as Set Label. Resize the button to fit the label appropriately.

Figure 6.13 shows our version of this view.

Figure 6.13

Figure 6.13 Your interface should include two labels, a field, and button—just like this!

Connecting Outlets and Actions

Our work in Interface Builder is almost complete. The last remaining step is to connect the view to the view controller. Because we already created the outlet and action connection points in the HelloNounViewController.h file, this will be a piece of cake!

Make sure that you can see both the document window and the view you just created. You're going to be dragging from the objects in the view to the File's Owner icon in the document window. Why File's Owner? Because, as you learned earlier, the XIB is "owned" by the HelloNounViewController object, which is responsible for loading it.

  1. Control-drag from the File's Owner icon to the label that you've established for output (titled <Noun Goes Here!> in the example), and then release the mouse button. You can use either the visual representation of the label in the view or the listing of the label object within the document window.
  2. When you release the mouse button, you'll be prompted to choose the appropriate outlet. Pick userOutput from the list that appears (see Figure 6.14).
    Figure 6.14

    Figure 6.14 Connect the label that will display output to the outlet.

  3. Repeat the process for the text field, this time choosing userInput as the outlet. The link between the input and output view objects and the view controller is now established.
  4. To finish the view, we still need to connect the button to the setOutput action. Although you could do this by Control-dragging, it isn't recommended. Objects that can trigger actions can have dozens of different events that can be used as a trigger. To make sure that you're using the right event, you must select the object in the view, and then press Command+3 or choose Tools, Connections Inspector. This opens the Connections Inspector, which shows all the possible events for the object.
  5. For a button object, the event that you're most likely to want to use is Touch Up Inside, meaning that the user had a finger on the button, and then released the finger while it was still inside the button.

    To do this for the button in our view, select the button, and then open the Connections Inspector. Drag from the circle beside Touch Up Inside to the File's Owner icon. When prompted for an action, choose setOutput (it should be the only option). The Connections Inspector should update to show the completed connection, as shown in Figure 6.15.

    Figure 6.15

    Figure 6.15 Use the Connections Inspector to create a link from the event to the action it should trigger.

Your view is now complete! You can safely exit Interface Builder, saving your changes.

Implementing the View Controller Logic

With the view complete and the connection to the view controller in place, the only task left is to fill in the view controller logic. Let's turn our attention back toward the HelloNounViewController.h and HelloNounViewController.m files. Why do we need to revisit the header? Because we'll need to easily access the userOutput and userInput variables, and to do that, we'll have to define these as properties, like this:

@property (retain, nonatomic) UITextField *userInput;
@property (retain, nonatomic) UILabel *userOutput;

Edit HelloNounViewController.h to include these lines after the @interface block. The finished file will read as follows:

#import <UIKit/UIKit.h>

@interface HelloNounViewController : UIViewController {
    IBOutlet UILabel *userOutput;
    IBOutlet UITextField *userInput;
}

@property (retain, nonatomic) UITextField *userInput;
@property (retain, nonatomic) UILabel *userOutput;
-(IBAction)setOutput:(id)sender;

@end

To access these properties conveniently, we must use @synthesize to create the getters/settings for each. Open the HelloNounViewController.m implementation file and add these lines immediately following the @implementation directive:

   @synthesize userInput;
   @synthesize userOutput;

This leaves us with the implementation of setOutput. The purpose of this method is to set the output label to the contents of the field that the user edited. How do we get these values? Simple! Both UILabel and UITextField have a property called text that contains their contents. By reading and writing to these properties, we can set userInput to userOutput in one easy step.

Edit HelloNounViewController.m to include this method definition, following the @synthesize directives:

-(IBAction) setOutput:(id)sender {
       userOutput.text=userInput.text;
}

It all boils down to a single line! Thanks to our getters and setters, this single assignment statement does everything we need.

Freeing up Memory

Whenever we've used an object and are done with it, we need to release it so that the memory can be freed and reused. Even though this application needs the label and text field objects (userOutput, and userInput), as long as it is running, it is still good practice to release them in the dealloc method of the view controller. The release method is called like this:

[<my Object> release]

Edit the HelloNounViewController.m file's dealloc method to release both userOutput and userInput. The result should look like this:

- (void)dealloc {
    [userInput release];
    [userOutput release];
    [super dealloc];
}

Well done! You've written your first iPhone application!

Building the Application

The app is ready to build and test. If you'd like to deploy to your iPhone, be sure it is docked and ready to go, and then choose iPhone Device from the drop-down menu in the upper left of the Xcode window. Otherwise, choose Simulator. Click Build and Run.

After a few seconds, the application will start on your iPhone or within the simulator window, as shown in Figure 6.16.

Figure 6.16

Figure 6.16 Your finished application makes use of a view to handle the UI, and a view controller to implement the functional logic.

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