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.
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.
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:
Archived objects. Also known as “flattened” or “serialized” objects—meaning that the object has been encoded in such a way that it can be saved to disk and later restored in memory. Archived objects contain information such as their size, location, and position in the object hierarchy. At the top of the hierarchy of archived objects is the File’s Owner object, a proxy object that, at runtime, becomes the actual object that owns the nib file (typically the one that loaded the nib file from disk).
Images. Image files that appear somewhere in your application’s interface, such as a button or image view.
Class references. Interface Builder can store the details of Cocoa objects and objects that you place into static palettes, but it does not know how to archive instances of your custom classes because it doesn’t have access to their code. For these classes, Interface Builder stores a proxy object to which it attaches your custom class information.
Connection information. Information about how objects within the class hierarchies are interconnected. When you save a document, information about the connections between the objects in the nib is archived along with the objects themselves.
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.
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.
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.
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.
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.
You use Interface Builder to define an application’s user interface. Open your application’s main nib file in Interface Builder:
Locate MainMenu.xib
in the Resources subgroup of your project.
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.
Make the window smaller by dragging the bottom-right corner of the window inward, as shown in Figure 4-1.
You can resize the window more precisely by using the Window Size inspector.
Select the window by clicking its titlebar or selecting its icon in the MainMenu.xib window.
Choose Tools > Inspector.
Click the Size icon, which looks like a yellow ruler.
In the Content Size & Position group, you can set the width, height, and default x and y coordinates of the window.
Use the width and height fields to enter a width of 400 and a height of 200, as shown in Figure 4-2.
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.
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.
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.
If the Library is not already open, shown in Figure 4-3—choose Tools > Library.
In the list at the top of the Library, open Library, then Cocoa, and select Views & Cells.
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.
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.
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.
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:
Select the text field, if it is not already selected.
Choose Duplicate (Command-D) from the Edit menu. The new text field appears slightly offset from the original field.
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.
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.
Text fields without labels would be confusing, so add labels to them by using the ready-made label object from the library.
Drag a Label element onto the window from the Cocoa library.
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.
Enter Exchange Rate per $1:
in the Title text field.
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:”.
Expand the labels to the left so their entire titles are visible, as shown in Figure 4-6.
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.
Select the third text field.
In the Inspector, navigate to the Text Field Attributes tab.
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.
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:
Drag the Push Button object from the library to the bottom-right corner of the window.
Double-click the button and change its title to Convert.
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.
Align the button under the text fields.
Drag the button downward until the layout guide appears, and then release it.
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.
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.
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:
Drag a Horizontal Line object from the Library to the Currency Converter window.
Drag the endpoints of the line until the line extends across the window, as shown in Figure 4-8.
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.
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.
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:
Dragging objects with the mouse in conjunction with the layout guides
Pressing the arrow keys (with the grid off, the selected objects move one pixel)
Using a reference object to put selected objects in rows and columns
Using the built-in alignment functions
Specifying origin points in the Size pane in the inspector
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.
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:
Select the Amount in Other Currency text label and extend the selection (Shift-click) to include the other two labels.
Choose Layout > Size to Fit to resize all the labels to their minimum width.
Choose Layout > Alignment > Align Right Edges.
Drag the labels towards the left edge of the window, and release them when the layout guide appears.
Select the three text fields and drag them to the left, again using the guides to help you find the proper position.
Shorten the horizontal separator and move the button into position again under the text fields.
Make the window shorter and narrower until the layout guides appear to the right of the text fields.
Select the Window object.
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.
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:
Select the Exchange Rate text field.
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.
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.
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.
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:
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.
Select initialFirstResponder
under Outlets.
The Currency Converter user interface is now complete.
Interface Builder lets you test an application’s user interface without having to write code. To test the Currency Converter user interface:
Choose File > Save to save your work.
Choose File > Simulate Interface.
Try various user operations, such as tabbing, and cutting and pasting between text fields.
When finished, choose Quit Cocoa Simulator from the application menu to exit test mode.
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