Mac OS X Reference Library Apple Developer
Search

Defining the View: Building the User Interface

Every application has a user interface. It can be a tedious and infuriating task to design user interfaces without a good program to help you. Interface Builder, an application supplied with Xcode, makes designing user interfaces simple, and so turns a tedious task into something easy.

This chapter teaches you how Interface Builder integrates with Cocoa. It guides you through building the user interface for your application. You learn where to locate the tools you need and how to use the features in Interface Builder to create the perfect user interface for your application.

User Interface Elements and Interface Builder

Interface Builder is an application that helps you design the user interface and connect the different parts of your application. It contains a drag-and-drop interface for UI design, and an inspector that allows you to view and change the properties of the various objects in your design, as well as the connections between them.

What Is a Nib File?

Every Cocoa application with a graphical user interface has at least one nib file. The main nib file is loaded automatically when an application launches. It contains the menu bar and generally at least one window along with various other objects. An application can have other nib files as well. Each nib file contains:

Windows and Menus in Cocoa

Windows have numerous characteristics. They can be onscreen or offscreen. Onscreen windows are “layered” on the screen in tiers managed by the window server. A typical Cocoa window has a title bar, a content area, and several control objects.

Key and Main Windows

Onscreen windows can carry a status: key or main. Key windows respond to keypresses for an application and are the primary recipient of messages from menus and panels. Usually, a window is made key when the user clicks it. Each application can have only one key window.

An application has one main window, which can often have key status as well. The main window is the principal focus of user actions for an application. Often user actions in a key window (typically a panel such as the Font window or an Info window) have a direct effect on the main window.

NSWindow and the Window Server

Many user interface objects other than the standard window are windows. Menus, pop-up lists, and pull-down lists are primarily windows, as are all varieties of utility windows and dialogs: attention dialogs, Info windows, drawers, utility windows, and tool palettes, to name a few. In fact, anything drawn on the screen must appear in a window. Users, however, may not recognize or refer to them as windows.

Two interacting systems create and manage Cocoa windows. A window is created by the window server. The window server is a process that uses the internal window management portion of Quartz (the low-level drawing system) to draw, resize, hide, and move windows using Quartz graphics routines. The window server also detects user events (such as mouse clicks) and forwards them to applications.

The window that the window server creates is paired with an object supplied by the Application Kit framework. The object supplied is an instance of the NSWindow class. Each physical window in a Cocoa program is managed by an instance of NSWindow or a subclass of it. For information on the Application Kit, see What Is Cocoa? in Cocoa Fundamentals Guide.

When you create an NSWindow object, the window server creates the physical window that the NSWindow object manages. The NSWindow class offers a number of instance methods through which you customize the operation of its onscreen window.

Application, Window, View

In a running Cocoa application, NSWindow objects occupy a middle position between an instance of NSApplication and the views of the application. (A view is an object that can draw itself and detect user events.) The NSApplication object keeps a list of its windows and tracks the current status of each. Each NSWindow object, on the other hand, manages a hierarchy of views in addition to its window.

At the top of this hierarchy is the content view, which fits just within the window’s content rectangle. The content view encloses all other views (its subviews), which come below it in the hierarchy. The NSWindow object distributes events to views in the hierarchy and regulates coordinate transformations among them.

Another rectangle, the frame rectangle, defines the outer boundary of the window and includes the title bar and the window’s controls. Cocoa uses the bottom-left corner of the frame rectangle as the origin for the base coordinate system, unlike Carbon applications, which use the top-left corner. Views draw themselves in coordinate systems transformed from (and relative to) this base coordinate system.

Creating the Currency Converter Window

Currency Converter has a main window that the user will interact with. This section guides you through the process of designing Currency Converter’s main window.

Create the Window

You use Interface Builder to define an application’s user interface. Open your application’s main nib file in Interface Builder:

  1. Locate MainMenu.xib in the Resources subgroup of your project.

  2. Double-click the nib file to open it in Interface Builder.

A default menu bar, the MainMenu.xib window, the Library, and an empty window titled Window appear when the nib file is opened.

nibs and xibs: Interface Builder stores object information in two forms. The xib file is analogous to a source file‚Äîit contains a detailed description of the interface specification, including various housekeeping information that Interface Builder uses while editing. At build time, the xib file is compiled down to a nib file, which is analogous to an object file. It contains only the information needed by your application at runtime. Because the xib file format is really just an editing format, this document will refer to both of these file types as nib files.

Resize the Window

Make the window smaller by dragging the bottom-right corner of the window inward, as shown in Figure 4-1.

Figure 4-1  Resizing a window manually

Resizing a window manually

You can resize the window more precisely by using the Window Size inspector.

  1. Select the window by clicking its titlebar or selecting its icon in the MainMenu.xib window.

  2. Choose Tools > Inspector.

  3. Click the Size icon, which looks like a yellow ruler.

  4. In the Content Size & Position group, you can set the width, height, and default x and y coordinates of the window.

  5. Use the width and height fields to enter a width of 400 and a height of 200, as shown in Figure 4-2.

    Figure 4-2  Resizing a window with the inspector

    Resizing a window with the inspector
  6. In Initial Position, you see a graphical representation of your window and your screen. Drag the window to the top-left corner of the box for a traditional default window position.

Changing the Title of the Window

The default title of the window is Currency Converter, the name of your project. If you wish, you can change the title in the Attributes tab of the inspector. Currency Converter is a fine title for your window, so leave it as it is.

Add the Text Fields

Interface Builder’s Library window contains user interface elements that you can drag into a window or menu to create an application’s user interface.

  1. If the Library is not already open, shown in Figure 4-3—choose Tools > Library.

    Figure 4-3  Cocoa Views and Cells in the Interface Builder Library window

    Cocoa Views and Cells in the Interface Builder Library window
  2. In the list at the top of the Library, open Library, then Cocoa, and select Views & Cells.

  3. Notice how in Figure 4-3 the icons have labels. To display labels, choose View Icons & Labels from the gear menu at the bottom of the Library window. This will make it easier to locate the objects you are looking for.

  4. Place a text field in the Currency Converter window.

    Find the Text Field item (shown highlighted in Figure 4-3) and drag the Text Field object from the library to the top-right corner of the window. Notice that Interface Builder helps you place objects according to the Apple human interface guidelines by displaying layout guides when an object is dragged close to the proper distance from neighboring objects or the edge of the window.

  5. Increase the text field’s size so it’s about a third wider.

    Resize the text field by grabbing a handle and dragging in the direction you want it to grow. In this case, drag the left handle to the left to enlarge the text field, as shown in Figure 4-4.

    Figure 4-4  Resizing a text field

    Resizing a text field
  6. Add two more text fields, both the same size as the first.

    There are two options: You can drag another text field from the palette to the window and make it the same size as the first one, or you can duplicate the text field already in the window.

    To duplicate the text field in the Currency Converter window:

    1. Select the text field, if it is not already selected.

    2. Choose Duplicate (Command-D) from the Edit menu. The new text field appears slightly offset from the original field.

    3. Position the new text field under the first text field. Notice that the layout guides appear and Interface Builder snaps the text field into place.

    4. To make the third text field, press Command-D again.

    As a shortcut, you can also Option-drag the original text field to duplicate it.

Assign Labels to the Fields

Text fields without labels would be confusing, so add labels to them by using the ready-made label object from the library.

  1. Drag a Label element onto the window from the Cocoa library.

    Dragging a label onto the window from the Cocoa library
  2. Make the label right aligned:

    With the label element selected, click the fourth button from the left in the Alignment area in the Text Field Attributes tab in the Inspector, as shown in Figure 4-5.

    Note: To open the inspector in Interface Builder, choose Tools > Inspector.

    Figure 4-5  Right aligning a text label in Interface Builder

    Right aligning a text label in Interface Builder
  3. Enter Exchange Rate per $1: in the Title text field.

  4. Duplicate the label twice. Set the title of the second text label to “Dollars to Convert:” and the title for the third label to “Amount in Other Currency:”.

  5. Expand the labels to the left so their entire titles are visible, as shown in Figure 4-6.

    Figure 4-6  Text fields and labels in the Currency Converter window

    Text fields and labels in the Currency Converter window

Change the Text Field Attributes

The bottom text field displays the results of the currency conversion computation and should therefore have different attributes than the other text fields. It must not be editable by the user.

  1. Select the third text field.

  2. In the Inspector, navigate to the Text Field Attributes tab.

  3. Click the Editable option to remove the checkmark, so users are not allowed to alter the contents of the text field. Leave the Selectable option checked so users can copy the contents of the text field to other applications.

Configure a Button

Providing a button to convert the currency amount creates a clear action for the user to take. To add a button to the Currency Converter window:

  1. Drag the Push Button object from the library to the bottom-right corner of the window.

  2. Double-click the button and change its title to Convert.

  3. In the Key Equiv. section of the Button Attributes inspector, click the gray box. Now press Return. A return symbol should appear in the gray box. This makes the button respond to the Return key as well as to clicks.

  4. Align the button under the text fields.

    1. Drag the button downward until the layout guide appears, and then release it.

    2. With the button still selected, hold down the Option key. If you move the pointer, Interface Builder shows you the distance in pixels from the button to the element over which the pointer is hovering.

    3. With the Option key still down and the pointer over the Amount in Other Currency text field, use the arrow keys to nudge the button so that its center is aligned with the center of the text field, as shown in Figure 4-7.

      Figure 4-7  Measuring distances in Interface Builder

      Measuring distances in Interface Builder

Add a Separator to Group Controls

The final interface for Currency Converter has a line separating the text fields and the button. To add the line to the Currency Converter window:

  1. Drag a Horizontal Line object from the Library to the Currency Converter window.

  2. Drag the endpoints of the line until the line extends across the window, as shown in Figure 4-8.

    Figure 4-8  Adding a horizontal line to the Currency Converter window

    Adding a horizontal line to the Currency Conveter window
  3. Move the Convert button up until the layout guide appears below the horizontal separator, and shorten the window until the horizontal layout guide appears below the Convert button.

Refining the Layout and View Functionality

The Currency Converter window now contains all the necessary objects for it to function as designed. This section guides you through formatting the window and menu to make it more user friendly.

Aligning Objects in a Window

In order to make an attractive user interface, you should visually align interface objects in rows and columns. “Eyeballing” the alignments can be very difficult, and typing in x/y coordinates by hand is tedious and time consuming. Aligning user interface elements is made even more difficult because the elements have shadows and user interface guideline metrics do not typically take the shadows into account. Interface Builder uses visual guides and layout rectangles to help you with object alignment.

In Cocoa, all drawing is done within the bounds of an object’s frame. Because interface objects have shadows, they do not visually align correctly if you align the edges of the frames. For example, Apple Human Interface Guidelines says that a push button should be 20 pixels tall, but you actually need a frame of 32 pixels for both the button and its shadow. The layout rectangle is what you must align. You can view the layout rectangles of objects in Interface Builder using the Show Layout Rectangles command in the Layout menu.

Interface Builder gives you several ways to align objects in a window:

The Alignment submenu in the Layout menu provides various alignment commands and tools, including the Alignment window, which contains controls you can use to perform common alignment operations.

Finalize the Window Size

The Currency Converter interface is almost complete. The finishing touch is to resize the window so that all the user interface elements are centered and properly aligned to each edge. Currently, the objects are aligned only to the top and right edges.

To finalize the Currency Converter window:

  1. Select the Amount in Other Currency text label and extend the selection (Shift-click) to include the other two labels.

  2. Choose Layout > Size to Fit to resize all the labels to their minimum width.

  3. Choose Layout > Alignment > Align Right Edges.

  4. Drag the labels towards the left edge of the window, and release them when the layout guide appears.

  5. Select the three text fields and drag them to the left, again using the guides to help you find the proper position.

  6. Shorten the horizontal separator and move the button into position again under the text fields.

  7. Make the window shorter and narrower until the layout guides appear to the right of the text fields.

  8. Select the Window object.

  9. Because you have made the window the perfect size for its components, you don’t want the user to resize the window. In the Attributes tab of the Inspector, uncheck Resize under the Controls section.

At this point the application’s window should look like Figure 4-9.

Figure 4-9  The Currency Converter final user interface in Interface Builder

The Currency Converter final user interface in Interface Builder

Enable Tabbing Between Text Fields

The final step in composing the Currency Converter user interface has more to do with behavior than with appearance. You want the user to be able to tab from the first editable field to the second, and back to the first. Many objects in the Interface Builder Library have an outlet named nextKeyView. This variable identifies the next object to receive keyboard events when the user presses the Tab key. A Cocoa application by default makes its “best guess” about how to handle text field tabbing, but you can improve the default behavior by explicitly setting the next key view according to the specific needs of your application. You set the next key view for an object by connecting the nextKeyView outlet.

To configure correct tabbing between text fields:

  1. Select the Exchange Rate text field.

  2. Control-drag a connection from the Exchange Rate text field to the Dollars to Convert text field, as shown in Figure 4-10. Press and hold the control key, then click on the Exchange Rate text field and drag the connection line to the Dollars to Convert text field. When the Dollars to Convert text field highlights, release the mouse button.

    Figure 4-10  Connecting nextKeyView outlets in Interface Builder

    Connecting nextKeyView outlets in Interface Builder
  3. Select nextKeyView under Outlets. This sets the next key view of the Exchange Rate text field (the object you dragged the connection from) to the Dollars to Convert text field (the object you dragged the connection to). At runtime, Cocoa uses the nextKeyView outlet to determine the next object to get keyboard focus after the Tab key is pressed.

  4. Repeat the same procedure, dragging from the Dollars to Convert text field to the Exchange Rate text field.

Now that you’ve set up tabbing between text fields, you must tell Currency Converter which text field will be selected first. You do this by setting an initial first responder.

Set the First Responder Text Field

The initialFirstResponder outlet determines the default selected object when your application starts. If you do not set this outlet, the window sets a key loop and picks a default initial first responder for you.

To set the initialFirstResponder outlet for the Currency Converter window:

  1. Control-drag a connection from the Window instance in the MainMenu.nib window to the Exchange Rate text field, as shown in Figure 4-11.

    Figure 4-11  Setting the initialFirstResponder outlet in Interface Builder

    Setting the initialFirstResponder outlet in Interface Builder
  2. Select initialFirstResponder under Outlets.

The Currency Converter user interface is now complete.

Test the Interface

Interface Builder lets you test an application’s user interface without having to write code. To test the Currency Converter user interface:

  1. Choose File > Save to save your work.

  2. Choose File > Simulate Interface.

  3. Try various user operations, such as tabbing, and cutting and pasting between text fields.

  4. When finished, choose Quit Cocoa Simulator from the application menu to exit test mode.

What’s Next?

In this chapter, you built the user interface for your application. You placed and organized all the various objects the user will interact with as they use the application, and you configured them to properly interact with each other. The next chapter will guide you through the creation of a controller that will connect the view you just created with the model you implemented in the previous chapter.




Last updated: 2009-08-03

Did this document help you? Yes It's good, but... Not helpful...