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

  • Print
  • + Share This
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.


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:


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;



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;


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 {

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.

  • + Share This
  • 🔖 Save To Your Account