Edit User Interfaces

Interface Builder is an Xcode editor that provides a graphical interface for the creation of user interface files. Like other Xcode editors, Interface Builder is fully integrated into the IDE, so you can write and edit source code and tie it directly to your user interface without leaving the Xcode workspace window.

When you create an OS X or iOS app, Xcode includes one or more user interface files in the project. These files, called nib files, have the filename extension nib or xib. Similarly, when you create a view controller, Xcode includes a nib file along with the header and implementation files for the new class. For iOS apps, you can use storyboards instead of nib files, as described in “Design the User Interface of Your iOS App with Storyboards.”

Create Your User Interface

Interface Builder, like other Xcode editors, has associated inspectors in the utility area. When you open a user interface file, your user interface objects appear in the editor area, and the Interface Builder inspectors appear in the utility area. You use these inspectors to configure the interface objects and to make connections between them. The Object and Media libraries in the library pane of the utility area are also for use with Interface Builder—you use these libraries to add new objects to your user interface.

Figure 4-1 shows a user interface file being edited. You can select objects and media files in the library pane and drag them onto the Interface Builder canvas. You can also open an assistant editor to view files associated with the selected in the primary editor.

Figure 4-1  A user interface file in Interface Builder

Display Your User Interface Objects

The dock on the left side of the editor pane shows the user interface objects and placeholders in the user interface file. The dock can display the high-level objects in an icon view (Figure 4-2) or in a list (called the outline view) showing all the objects nested in higher-level objects (Figure 4-1). Storyboard files show only the outline view in the dock; however, each scene in the storyboard has its own scene dock displayed below it when you select the scene.

Figure 4-2  Icon view for placeholders and objects in Interface Builder

Add new objects to an Interface Builder document using the outline view, a hierarchical tree that reflects the parent-child relationships between the objects in the nib file.

Note that you can also use the Interface Builder jump bar to select any object in the interface.

Connect to Other Files Using Placeholders

There are two kinds of objects displayed in the Interface Builder dock: interface objects and placeholders. Interface objects are created when the user interface file is loaded and typically comprise the bulk of the objects. Placeholders are files that live outside of the user interface file but are intimately tied to the contents of the nib file. There are normally three placeholders in a nib file:

  • File’s Owner

  • First Responder

  • Application

File’s Owner

File’s Owner represents the user interface file’s controller object. File’s Owner is the most commonly used placeholder in user interface files. The File’s Owner placeholder is the main bridge between your app and the contents of the user interface file.

You can designate any object in your app as the File’s Owner of an interface file. You tell Interface Builder the class of the File’s Owner so it knows what connections to make available. Typically, the File’s Owner is an instance of a controller class that manages the interactions with the views and other controller objects inside the interface file.

bullet
To configure the File’s Owner placeholder
  1. Select the File’s Owner placeholder in the Interface Builder dock.

  2. Open the Identity inspector.

  3. In the Class field of the Custom Class section, set the class of the File’s Owner to the corresponding class in your app.

    The following table lists some of the standard classes that are commonly used to represent File’s Owner in apps:

    Subclass of

    Operating system

    Description

    NSDocument

    OS X

    Document-based apps store the document window and other required interface objects in a nib file. The File’s Owner of this nib file is traditionally the document object itself.

    NSWindowController

    OS X

    Window controllers provide a great deal of automatic management for nib files and are especially useful when your nib file contains only one window.

    NSViewController

    OS X

    A view controllers manage custom accessory views and other view-based content.

    UIViewController

    iOS

    Custom UIViewController objects are often used to manage the content view for a distinct screen’s worth of content. UI view controllers provide automatic interface-loading and purging support.

    Any custom NSObject subclass

    OS X and iOS

    You can use practically any object you like for manual control of an interface file. It is up to you to define the relationships between this class and the objects in the interface file.

  4. Control-click the File’s Owner object to see the outlets and actions defined by that object’s class.

To learn about outlets and actions, see “Manage Connections Between User Interface Objects.” You can use these outlets and actions to connect other objects to File’s Owner. You can use File’s Owner as a target for your bindings. For information about connecting to File’s Owner, see “Make Connections Directly Between User Interface Objects and Your Source Files.”

First Responder

The First Responder placeholder represents the first object in the responder chain, which is determined dynamically at runtime by the AppKit and UIKit frameworks.

bullet
To add new action messages to the First Responder’s supported list
  1. Select the First Responder placeholder object in your Interface Builder document.

  2. Open the Attributes inspector.

  3. Click the Add (+) button at the bottom of the User Defined section to create an action method entry.

  4. Double-click the method name in the Action column and type the name of the method.

  5. Select the class in which the method will be defined from the pop-up list in the Type column.

  6. After you are done making connections in Interface Builder, add the code for the method to the header and implementation class files in your project that you specified in step 5.

    The name of the method must match the name specified in step 4.

Adding action method to the First Responder placeholder does not add the corresponding method definition to your Xcode source files. All it does is let Xcode know that such a method exists in one of the objects in the responder chain of your project. It is up to you to ensure the method names you add to the First Responder placeholder match the names of the methods in your code. Xcode does not validate these method names for you. At runtime, if a method name is misspelled or does not exist in an object, the corresponding action message is never received by the target object.

Interface Builder does not prevent you from deleting the standard system messages associated with the First Responder placeholder. Doing so removes the message name only from the current interface file.

When the operating system sends a message to your app, the message is sent to your app’s first responder. The first responder is typically the currently selected object or the object with the current focus in the frontmost window. You use the first responder to make connections to any messages that operate on the current selection or need to be handled by your frontmost window or document. For example, if you wanted a menu command to be handled by your frontmost window, you would dispatch that command to your first responder.

The First Responder placeholder displays all the actions that are either supported natively by the operating system or defined in your Xcode source files.

Application

In OS X user interface files, the Application placeholder gives you a way to connect the outlets of your app’s shared NSApplication object to custom objects in the interface file. The default application object has outlets for its delegate object and, in Mac apps, the menu bar. If you define a custom subclass of NSApplication, you can connect to any additional outlets and actions defined in your subclass.

At load time, the interface-loading code automatically replaces the Application placeholder with the shared application object from your app.

Select Objects in a User Interface File

In Interface Builder, you can usually select an object in an nib or storyboard file by clicking it in the canvas. Many objects are compound, however, such as a text field that contains a number formatter.

bullet
To select an object using the dock
  1. Expand the dock to show the outline view.

  2. Use the disclosure triangles to open the objects containing the object you want to select.

  3. Select the object in the outline view.

bullet
To select an object using the jump bar
  1. If the top-level window or user interface object is not already displayed on the Interface Builder canvas, select the window or object in the dock.

  2. Select an object in the jump bar that contains the object you want to select.

  3. Navigate through the jump bar to the object you want to select.

    image: ../art/interface_builder_jump_bar.png

Lay Out User Interface Controls Using Content-Driven Rules

Interface Builder supports the AppKit Auto Layout feature. Auto Layout, available starting with OS X v10.7 Lion, uses relationships called constraints to govern the layout of objects in the user interface. This feature is a complete replacement for the autoresizing mask. As you make changes to any view or control in Interface Builder (move it around, resize it, change an attribute, add a subview, and so forth), Interface Builder automatically adds and removes constraints based on the new layout. When you enable this feature, Interface Builder shows the constraints as you work, as shown in Figure 4-3.

Figure 4-3  Auto Layout

To use Auto Layout in your project, you turn on the feature on each interface file you want to use it on.

Create user interfaces that adapt dynamically to content and sizing changes by enabling Auto Layout.

Interface Builder treats constraints like other objects in an interface file. As you lay out objects in the canvas, Interface Builder adds constraints to the object or its containing view. There are three ways to see layout constraints:

bullet
To see the constraints of a container view or an object in a user interface file
  1. Open the user interface file.

  2. View the document outline in the Interface Builder dock.

  3. Select the view or object for which you want to view constraints.

  4. View the constraints in the Constraints list for the container view or control.

    image: ../art/interface_bulder-view_constraints.png

Align and Pin Objects in Your User Interface

As you lay out object in your user interface (by aligning them with other objects, or pinning them to the container view), Interface Builder adds constraints that reflect your layout.

Position objects in relation to other objects or their container.

Any constraint that you have modified or added manually is a custom constraint and is shown on the canvas with a thicker line than used for the automatic constraints. In the figure, the custom constraint is the one affecting the width, and the connections to the superview are automatic constraints.

Figure 4-4  Custom constraint

Table 4-1 lists the types of layout constraints.

Table 4-1  Layout constraints

Constraint

Figure

Notes

Size (width or height)

image: ../art/constraints_size.png

Select the object and choose Editor > Add Constraint > Width or Editor > Constraint > Height. Use the Attributes inspector to specify the value of the constraint. For example, “equal to 80 pixels,” or “less than or equal to 150 pixels.” The figure shows a constraint that keeps the width of a button greater than or equal to some number.

Equal size

image: ../art/constraints_equal_size.png

Select all the objects that you want to include and then choose either Equal Widths or Equal Heights from the Editor > Add Constraint menu. If all the objects involved maintain their intrinsic content size (see “Allow Objects to Maintain Their Intrinsic Content Size”), then the width or height of the objects is that of the largest object in the group. If one of the objects has an explicit size, then the other objects assume the same explicit size.

Spacing

image: ../art/constraints_spacing.png

Select two objects and then choose either Horizontal Spacing or Vertical Spacing from the Editor > Add Constraint menu. The figure shows a button and a text field with a set distance between them.

Superview-spacing

image: ../art/constraints_container.png

Select an object an choose one of the superview commands from the Editor > Add Constraint menu: Leading Space to Superview, Trailing Space to Superview, Top Space to Superview, or Bottom Space to Superview. Use the Attributes inspector to specify the space between the object and its container. The figure shows a constraint holding the leading edge of a button the standard aqua space from the leading edge of the container.

Alignment

image: ../art/constraints_aligment.png

Select all the objects that you want to include and then choose an item from the Editor > Alignment menu. Alignment constraints are drawn as a straight line rather than an I beam. For example, in the figure, the label and text field are aligned along their baselines.

You can edit constraints to specify such features as absolute or relative widths or heights.

bullet
To edit a constraint
  1. Edit the properties of the constraint in the Attributes inspector.

Allow Objects to Maintain Their Intrinsic Content Size

If there are no explicit constraints for width or height, an object assumes its intrinsic content size, which is the minimum size the object needs to be to hold its contents. For buttons, that might be the title, an image, or both. For text fields, the contents consist of the string and the bezel, for a combo box, the string in the text field and the disclosure button, and so forth.

Some objects have an intrinsic content height, but not width. Others, such as buttons, have both an intrinsic height and width. Some objects, such as table views, have no intrinsic content size. When an object is set to maintain its intrinsic content size, it resizes as needed to accommodate changes, such as differences in the length of text strings due to localization.

As opposed to an object with an explicit size, an object that maintains its intrinsic content size (and has no other size restraints) does not have the I-beam size constraint under it, as shown in Figure 4-5. To specify intrinsic content size, select the object and choose Size to Fit from the Editor menu.

Figure 4-5  Button set to maintain its intrinsic content size

Override Automatic Layout Constraints

Interface Builder helps you to lay out user interface control by adding automatic constraints as you place objects in a view. For example, if you place a button in the top-left corner of a window following the layout guides, Interface Builder pins the button to the top-left edges of the window (Figure 4-6).

Figure 4-6  Automatic layout constraints

This means that the button’s left edge is pinned to the window’s left edge. If the user resizes the window by moving its left edge, the left edge of the button maintains its distance from the left of the window as the user drags the window’s edge. The button moves with the left edge. However, if the user drags the window’s right edge, the button does not move.

To pin the button to the right edge of the view, you would select the button and choose Editor > Pin > Trailing Space to Superview (this action adds a constraint from the trailing edge of the button to the right edge of the containing view, shown in Figure 4-7). Now the button is pinned to both left and right edges. Resizing the window by dragging the left or the right border results in the button changing its size to meet both horizontal-spacing constraints.

Figure 4-7  Custom layout constraints

Set Priorities to Resolve Potential Conflicts Between Layout Constraints

Occasionally, two constraints can come into conflict when a view is being resized. For example, you might have set your buttons not to get below a certain size, and also set a minimum width for the view containing the buttons. You can determine whether the minimum size for the window in this case is determined by the view width constraint or the button width constraint by specifying a lower priority for one than the other. For example, if you set the priority for the button width constraint to 50 while the priority for the view width constraint is 1000, Auto Layout will allow the view to be reduced to its minimum width even if it means reducing the size of the buttons.

Design the User Interface of Your iOS App with Storyboards

With storyboards you specify your app’s user interface in terms of scenes with transitions between them, and the controls used to trigger the transitions. Thus you can lay out every possible path through your app graphically, greatly reducing the amount of code you need to write for a complex multiscreen app.

To create a project that uses storyboards for its user interface files, select the “Use Storyboard” option when you create the project.

In a storyboard each object in a view controller that can cause a change in the display, is connected to another view controller that configures and implements the subsequent scene.

image: ../art/interface_builder-storyboard.png

The arrows between view controllers represent the segues from one scene to another.

bullet
To configure a segue
  1. Select the segue in the document outline or in the canvas.

  2. Configure the segue in the Attributes inspector.

The simplest segue style is Push. The Modal style lets you specify standard transition types, such as flip and cross-dissolve. You can also choose the Custom style to use a custom transition. See "Creating Custom Segues".

Create User Interface Classes

If you need a custom view object or a view controller, you create the classes in the project navigator. Once you’ve created the interface and implementation files, you can connect user interface objects in a user interface file directly to your code files or you can add connections in the interface files between interface objects and existing outlets and actions in the user interface file.

When you create an OS X app project or an iOS nonstoryboard-based app project, Xcode includes a nib file for your main view and a view controller class. When you create an iOS storyboard-based app project, Xcode includes a storyboard and a view controller class. The view controller is represented in the nib file as the File’s Owner object. When you need a new nib file for a project, you should create the interface and implementation files for the controller first. In many cases, Xcode creates a nib file as well. As nib files usually have controllers already assigned to them, it is rarely necessary to add a separate view controller to a nib file.

Add a New Nib File

When you need a new nib file, first add interface and implementation files for the controller to the project. In some cases, you automatically get a new nib file as well. If not, you can then add a nib file and link it to the controller.

bullet
To add a new nib file to a project
  1. Choose File > New > File and select the template type for your new controller files, and click Next.

    image: ../art/new_file-objc_ui_class.png
  2. Specify the name and parent class of the new controller, select the “With XIB for user interface” option, and click Next.

    In the figure, for example, the new class will be a subclass of NSWindowController named MyWindowController.

    image: ../art/new_file-objc_ui_class-classname_and_xib.png
  3. Specify the location for the new files, and click Create.

    Xcode creates a header, implementation, and nib files and adds them to your project.

To see the outlets and actions provided by the parent class of the File’s Owner, click the File’s Owner object in the dock and open the Connections inspector. To add new actions or outlets to the nib file’s controller, see “Make Connections Directly Between User Interface Objects and Your Source Files.”

Add a Custom View

A custom view is a subclass of one of the standard views classes, such as NSView or NSButton. To add a custom view, first create the view’s class in the project navigator, then add the view to your nib.

To add a custom view to a user interface file:

  1. Add the header and implementation files to your project.

    Select the appropriate Objective-C class template, your custom class’s name, and its superclass.

  2. Add a custom view to the interface file.

  3. Select the custom view and specify its class as the class you added in step 1 by identifying it in the Identity inspector.

    image: ../art/interface_builder-add_custom_view.png

Add a New Controller

Every nib file is created with a File’s Owner object, which you link to the controller for the file. In the rare event that you need to add another controller to a nib file (to control a subview, for example), you need to create source files for the controller and add a controller object to the nib file so that you can make connections to the controller.

To add a controller to a user interface file:

  1. Add the header and implementation files to your project.

    Select the Objective-C Class template, enter your custom controller class’s name, and specify NSController as its superclass.

  2. From the Object library, drag an Object object to the Interface Builder dock.

  3. Select the custom view and specify its class as the class you added in step 1 by identifying it in the Identity inspector.

    image: ../art/interface_builder-add_custom_controller.png

To see the outlets and actions provided by the controller, select the controller object in the dock and open the Connections inspector. To add new actions or outlets to the controller, see “Make Connections Directly Between User Interface Objects and Your Source Files.”

Simultaneously Design and Implement User Interface Objects Using Multiple Editors

When you use custom subclasses in your interface, or add outlets and actions to a controller, you can use an assistant editor pane to work on your interface code at the same time as your UI design.

bullet
To design and implement user interfaces at the same time
  1. Select your user interface file in the project navigator so that Interface Builder becomes the primary editor.

  2. Choose View > Assistant Editor > Show Assistant Editor (to open an assistant editor pane).

    The assistant editor pane contains a source editor with the implementation file for the controller in charge of the interface file.

    image: ../art/interface_builder-design_and_source.png

    If the assistant editor does not automatically display the file you want, use the jump bar in the assistant editor pane to open the file you want to view.

Manage Connections Between User Interface Objects

The objects in your user interface must communicate with each other and with your source code if your app is to interact with the user. To specify which messages are sent and received, you use create connections between objects. There are four fundamental types of connections you can create:

Make Connections Directly Between User Interface Objects and Your Source Files

You can make a connection directly from a user interface object to the appropriate header or implementation file, and, if needed, Xcode inserts code directly into your header and implementation files.

Figure 4-8 shows a connection being made to an existing IBAction statement.

Figure 4-8  Making a connection to source code from a user interface file

Connect an object directly to the declaration of a new outlet in a source file.

Connect an object to the declaration of a new action method in a header file.

If you make the connection to a header file, Xcode also inserts code in the corresponding implementation file as appropriate. For example, if you use Interface Builder to place a new action called loadComposition in a header file, Xcode inserts the line

- (IBAction)loadComposition:(id)sender;

in the header file and, in the corresponding implementation file, Xcode inserts

- (IBAction)loadComposition:(id)sender {
}

You can then put your implementation code for the loadComposition method directly into the implementation file.

Note that, because the Control-click key combination is used by Interface Builder to make connections, you must Control-click on the canvas—not on any object in the user interface—to get the shortcut menu with the list of help articles for Interface Builder.

Add Outlets and Actions to Classes Programmatically

The easiest way to add an outlet or action to your controller class is by dragging from an user interface object, as described in “Make Connections Directly Between User Interface Objects and Your Source Files.” However, in some cases you might want to define certain outlets or actions in your code before configuring connections in Interface Builder. To do so, you use the IBOutlet, IBOutletConnection, and IBAction keywords in your code. Because Xcode indexes both header and implementation files, you can add outlets and actions to the implementation file only so that you do not expose your connections to clients who use your public header files.

Use the Connections Inspector or the Connections Panel to Make Connections

You can manage outlet, action, and event connections by using the Connections inspector or the connections panel. These two tools provide the same basic behavior but do so in slightly different ways. The Connections inspector displays the connections associated with the selected object. Changing the selection changes the contents of the inspector. The connections panel is an on-demand window that you open by Control-clicking the object. The connections panel displays the connections for the same object until you dismiss the panel. You can open multiple connections panels at the same time.

You can use the techniques described in this section to make connections that are already defined in the source code or SDK frameworks. To define new outlets, actions, or events, see “Make Connections Directly Between User Interface Objects and Your Source Files.”

bullet
To make a quick connection
  1. Control-drag from the source object to the target object. If a connection is possible with the target object, the target object is highlighted.

  2. When you complete the drag, Interface Builder displays a prospective list of actions and outlets.

  3. Select an outlet (of the source object) or an action or event (of the target object) to create the connection.

When you use the Control-drag gesture to create a connection for an action or event, the final part of the task involves picking the action or event from a list. Outlet connections display a similar list. If there are previous connections that have the same name, the menu items to pick those names are flagged. If a connection identical to the one being made already exists, the menu item is flagged with a dot. If a connection exists with that name, but to a different object, it is flagged with a dash.

bullet
To make a connection using the Connections inspector
  1. Control-click an object and release the mouse button to display the panel.

  2. Drag from the circle on the right side of the action, outlet, or event you want to connect to the target object.

    If the target of a connection is not visible, placing the pointer over its parent object causes the parent to open and reveal its children.

    If a connection is possible with the target object, the target object is highlighted.

  3. If you are using the connections panel to configure the sent action or referencing outlet for the object, when you complete the drag, Interface Builder displays a list of the target object’s action methods or outlets. Select an action method or outlet from the list to finish the connection.

  4. If you want to select other objects in your interface but do not want the connections panel to disappear, drag the panel to a new location.

    You do not have to drag the window far; even dragging it a single pixel is sufficient. Note that if you do this, you must dismiss the window yourself by clicking its close box when you are done.

After you establish a connection, the connections panel fills the circle next to that action or outlet and displays information about the connection. Each connection also includes a close box icon that you can use to break the connection. If a received action has multiple source objects associated with it, the panel displays a disclosure triangle, which you can use to reveal the individual connections. If you select a connection, Interface Builder displays a path control at the bottom of the panel and a "take me there" button for the selected connection.

The connections panel remains visible as long as you use it. If you click outside the panel (by selecting a different user interface object, for example) Interface Builder dismisses the panel automatically to get it out of your way. You can also dismiss the panel explicitly by clicking its close box.

You can start an action or event connection at the source object to connect from the sent action selector (for Mac apps) or to connect from an event (for iOS apps). You can start a connection at the target object to connect one of its action methods to a source object.

When connecting from target to source, you can connect each action method multiple times. After you make the first connection, the circle next to the action method is filled to show that there is an associated source object. To connect an additional source object, drag from the circle to the target object. Performing this action does not remove the original connection.

Like action connections, you can create outlet connections starting at either the source or target object. Using an OS X SDK, only one object at a time may be connected to a given outlet. In iOS SDKs, multiple objects can be connected to a given outlet.

You can also use the Connections inspector to make and view connections. The Connections inspector provides a summary of the outlets and actions (or events) of the selected object. You can use the inspector to view the status of connections, to create new connections, and to remove existing connections.

bullet
To make a connection using the Connections inspector
  1. Open the Connections inspector and select the object from which you want to connect.

  2. Drag from the circle next to the entry you want to connect to the target object for the connection. (If the target of a connection is not visible, placing the pointer over its parent object causes the parent to open and reveal its children.) If a connection is possible with the target object, the target object is highlighted when you hold the pointer over it.

  3. If you are using the Connections inspector to configure the sent action or referencing outlet for the object, when you complete the drag, Interface Builder displays a list of the action methods or outlets of the target object. Select an action method or outlet from the list to finish the connection.

After you establish a connection, the Connections inspector fills the circle next to that entry and displays information about the connection. Each connection also includes a close box icon that you can use to remove the connection. If a received action has multiple source objects associated with it, the Connections inspector displays a disclosure triangle, which you can use to reveal the individual connections.

Modify Connections

At times you may need to remove an existing connection and replace it with a new one. You can use either the Connections inspector or the connections panel to do so.

Change an object’s connections to other objects in a nib file using the connections panel. After making a connection directly to your source code, you may need to change or remove the connection. The connections window shows you all the connections to and from an object, and makes it possible to change or remove them.

Connect Menu Items to Your Code or Your First Responder

There are two common techniques for handling menu commands in a Mac app:

  • Connect the corresponding menu item to a first responder method.

  • Connect the menu item to a method of your custom application object or your application delegate object.

Of these two techniques, the first is somewhat more common given that many menu commands act on the current document or its contents, which are part of the responder chain. The second technique is used primarily to handle commands that are global to the application, such as displaying preferences or creating a new document. It is possible for a custom application object or its delegate to dispatch events to documents, but doing so is generally more cumbersome and prone to errors.

Configure Connections Between Model and View Objects

Cocoa bindings are a controller-layer mechanism used to synchronize the view and model layers of Mac apps. Bindings establish a mediated connection (through a controller object) between a view and a piece of data, binding them in such a way that a change in one is reflected in the other.

One of the advantages of using bindings over traditional glue code is that you can use Interface Builder to configure them. You can configure the bindable properties of an object in the Interface Builder Bindings inspector. The configured bindings are saved in the nib file and re-created at runtime like other types of connections.

You configure bindings in Interface Builder by starting at the object that exposes a bindable property—typically, a view or controller object. You then use the Bindings inspector to specify the target of the binding and the binding options. You must configure each binding separately and each binding can be attached to a different target object. The target of a binding is always one of the recognized controller objects in your nib file, which typically includes the File’s Owner, the application, the shared user defaults controller, and any custom controller objects (especially NSController objects) you add to the nib file.

For more information about how Cocoa bindings work, see Cocoa Bindings Programming Topics.

Create and Configure a Binding with the Bindings Inspector

In Interface Builder, you typically bind views and controller objects in your nib file to the data in your custom controller objects.

bullet
To create a binding
  1. Create the views needed to display your data.

  2. Create any intermediate controller objects needed to manage your data. (Typical controller objects include instances of your custom NSDocument or NSWindowController subclasses, NSController subclasses, or custom NSObject subclasses that you create to manage your data structures.)

  3. Use the Bindings inspector to configure each binding.

    image: ../art/interface_builder-bindings_inspector.png

Although each binding displays several configuration options, the most important part of a binding is the target of the binding. You must configure, at a minimum, the following fields for any given binding:

  • Bind to

  • Model Key Path

The Bind to field specifies the controller object to use as the starting point for accessing the target data.

The Model Key Path field contains a string representing the key path for the data. Key path strings are of the form <property_name>[.<property_name>]*. The first property name in this string is a property on the controller object specified by the Bind to field. Each subsequent property name corresponds to a property of the object returned by the previous property name. Say, for example, that you have a custom controller object and the key path string person.address.street. The person property returns the person object of the bound controller. The address property returns the address of the corresponding person object. And the street property returns the data value stored in the address object.

Create a Binding by Dragging Directly to Your Header File

As with outlets and actions, you can drag directly from an object in your nib file to code in your header file to create a binding.

Bind an object directly to a declaration in a header file.

Key Paths Are Dependent on Your Data Model

The best way to understand how to bind key paths in Interface Builder is to go through some examples. The following sections show how to bind a text field to an NSNumber object to display the number value in that text field. In each successive example, the data model used to access the number value gets progressively more complex, and so the bindings must be adjusted in accordance with the increased complexity.

For bindings examples, see Cocoa Bindings Programming Topics.

Bind a Document Object Directly to a Value

The simplest key path occurs when you bind a user interface object directly to a data value in your code.

bullet
To set up a simple object-data relationship
  1. Set the target object to the document’s File’s Owner.

    The document object must be KVC compliant.

  2. Set the model key path to the name of the instance variable.

Bind a Document Object to a Data Object Through an Object Controller

Frequently, the File’s Owner isn't the main data-containing object. Instead, you typically have other data objects (often held in a collection), referenced by the File’s Owner. In this case, you should add an object controller (an NSObjectController object) and bind the user interface object (the view object) to the data object through the controller object and the File’s Owner. The controller object acts somewhat like a buffer layer between your view and data object and the controller object acts as a placeholder for the document’s current Entry object, providing a valid binding target even if the document’s entry property becomes nil.

bullet
To bind to a data object through an object controller
  1. Set the target object to the NSObjectController object.

    The object controller, document object, and data object must all be KVC compliant.

  2. Choose either selection or selectedObjects in the Controller Key pop-up menu.

  3. Add the target property in the Model Key Path field.

    OS X combines the strings in the Controller Key and Model Key Path fields to get the final key path.

Bind to a Collection of Objects Through an Object Controller

Using controller objects, binding to a collection of objects is as simple as binding to a single object. In fact, the bindings themselves are almost identical. Instead of binding to a single object, you bind the view to a collection of objects through an NSArrayController object. The array controller manages both the collection of objects and the list of indexes corresponding to the selected objects and uses that information to provide an appropriate value to the text field.

bullet
To bind to a collection of objects
  1. Bind the text field to an NSArrayController object’s selection property, which represents the currently selected Entry object.

  2. Specify the quantity string for the key path.

Configure the Binding Attributes to Customize the Binding

Although the Bindings inspector may seem complex at first, for many bindings, you need to configure only a few options initially. You may not need to configure every option every time (except for the Bind to and Model Key Path fields). During your initial design phase, you can probably leave most of the options configured with their default values. As you improve your design, you can customize the options more until you have the behavior you want.

For a complete list of bindings available for a given view or controller object, see Cocoa Bindings Reference.

Bind to Objects in a Custom Tree Data Structure

If your program contains a custom tree data structure, you can use an NSTreeController object to coordinate bindings to the objects in that data structure. Tree controllers are often used to bind data objects to an NSBrowser or NSOutlineView object in order to display hierarchical sets of data to the user.

bullet
To configure a tree controller object
  1. Add the tree controller object to your document and select it.

  2. Open the Attributes inspector.

  3. Fill in the Object Controller section.

    • In the Class Name field, specify the class name of the objects in the tree.

    • Optionally, specify any custom keys of the tree objects that you want to expose in the Model Key Path field of the bindings inspector.

  4. Fill in the Tree Controller section.

    • In the Children field, specify the key path for the property that identifies the child nodes of a given tree object.

    • In the Count field, specify the key path for the property that indicates how many children a given tree object has. (This key path is optional.)

    • In the Leaf field, specify the key path for the property that identifies whether the current tree object is a leaf node. (This key path is optional but recommended because it can improve the tree controller’s performance as it navigates your tree at runtime.)

For more information on using tree controllers, see Cocoa Bindings Programming Topics.

Bind to Your Application Preferences

An NSUserDefaultsController object is most often used when implementing a preferences window or in any situation where you want to bind a view to values in the defaults database. Although you can add a new NSUserDefaultsController objects to your nib file, you generally do not need to do so. Interface Builder provides a shared user defaults controller object that you can use to bind to your application’s preferences.

bullet
To use the shared defaults controller to implement your application’s preferences window
  1. Select the control you want to bind to a preference.

  2. Open the Bindings inspector.

  3. In the appropriate binding for your control, set the Bind to field to Shared User Defaults Controller.

  4. In the Model Key Path field, enter the key name of the preference you want to associate with the control.

For more information on configuring user defaults bindings, see "User Defaults and Bindings" in Cocoa Bindings Programming Topics.


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