Hour 8. Creating User Interfaces


What You’ll Learn in This Hour:

What the Interface Builder editor does and what makes it special

The differences between XIB and storyboard files

How to create user interfaces using the Object Library

The use of Auto Layout features in OS X

How to instantiate any object in an Interface Builder document


Over the past few hours, you’ve become familiar with the core Xcode functions, including project management and coding features. Although these are certainly important skills for becoming a successful developer, there’s nothing quite like building your application interface and seeing it come alive on the screen.

In this hour, we introduce the Interface Builder editor. Interface Builder provides a visual approach to application interface design, but behind the scenes, it does much, much more. As you read through this hour, keep in mind that Interface Builder is integral to the OS X/iOS application development workflow. You’re going to be seeing a lot more of it through the rest of the book.

What Is Interface Builder?

Let’s get it out of the way up front: Yes, the Interface Builder editor (or IB for short) does help you create interfaces for your applications, but it isn’t a just a drawing tool for GUIs; it helps you symbolically build application functionality without writing code. This translates to fewer bugs, less development time, and easier-to-maintain projects.

Originally a standalone application, it is now integrated into Xcode 4. In this hour, we focus on navigating through Interface Builder’s components. We also spend time with it over the next 2 hours—getting to know how it ties back to your code files and its iOS-specific features.

The Interface Builder Approach

Using Xcode and the Cocoa toolset, you can program OS X and iOS interfaces by hand—instantiating interface objects, defining where they appear on the screen, setting attributes for the objects, and, finally, making them visible. Over the years, there have been many different approaches to graphical interface builders. One of the most common implementations is to enable the user to “draw” an interface, but behind the scenes create the code that generates that interface. Any tweaks require the code to be edited by hand—hardly an acceptable situation.

Another tactic is to maintain the interface definition symbolically but to attach the code that implements functionality directly to interface elements. This, unfortunately, means that if you want to change your interface, or swap functionality from one UI element to another, you have to move the code as well.

Interface Builder works differently. Rather than autogenerating interface code or tying source listings directly to interface elements, IB builds live objects that connect to your application code through simple links called connections. Want to change how a feature of your app is triggered? Just change the connection. As you learn a bit later, changing how your application works with the objects you create in Interface Builder is, quite literally, a matter of connecting or reconnecting the dots as you see fit.

Beyond the UI

Something that isn’t immediately obvious to many developers is that Interface Builder isn’t just for interfaces. In fact, you can use it to instantiate any object that you want, even your custom classes. When your interface file is loaded, OS X and iOS create instances of any objects described in the file (or scene).

As long as you provide a connection to your object (which you learn about in the next hour), you can create these instances exactly as if you had allocated and initialized them in code. Why is this valuable? Because it saves time and simplifies development. Need an instance of a controller to manage your interface? Add a controller object. The more complex your applications become, the more you’ll appreciate the code you don’t have to write.

Interface Builder XIB Versus Storyboard

One of the most confusing aspects of writing about the Interface Builder editor is that it works a bit differently between OS X and iOS applications.

In an OS X application, your work in Interface Builder results in an XML file called an XIB or (for legacy reasons) NIB file, containing a hierarchy of objects. Your application delegate loads the XIB file and becomes what is called the File’s Owner for the objects in the XIB file. Other classes can load additional XIB files to further build the application interface, becoming the File’s Owner for whatever objects they load. This parent-children relationship is clearly denoted in Interface Builder and makes it easy for interface objects to connect to the classes that instantiated them.

Unlike OS X applications that lend themselves to being built up from multiple components (multiple windows, palettes, etc.), iOS applications focus on a single, fullscreen interface. That interface may certainly go through transitions from one appearance to another, but the application only presents a single “face” at a time.

Storyboards provide a way of defining multiple scenes within a single file: a storyboard file. When an application starts, it loads a default storyboard file and scene. The objects within that scene are instantiated, just like a XIB file. Using code or point-and-click connections (which you learn about in Hour 10, “Creating iOS Application Workflows with Storyboards”), you can transition to other scenes and so on.

Unlike a XIB, a storyboard does not have a File’s Owner object that it can reference. Instead, each scene must define a view controller class (that is, a class that will manage the objects in the scene). You can certainly add view controllers to your OS X XIB files and develop in a manner similar to iOS, but Apple forces a more structured approach with the storyboard approach.


Where It All Begins

By default, OS X application projects are set to load their initial interface from MainMenu.xib. iOS projects load the storyboard from MainStoryboard.storyboard or from MainStoryboard_iPad.storyboard and MainStoryboard_iPhone.storyboard for universal projects.

You can change this behavior by selecting the top-level project group in the Project Navigator, selecting your application target, then using the Main Interface or Main Storyboard fields in the Summary area to choose a new file, as shown in Figure 8.1.

Image

Figure 8.1. Set the interface file loaded when the application starts.

In addition, you can load XIB files and storyboards dynamically throughout your application. This is often accomplished in OS X with the NSViewController instance method initWithNibName:bundle, and in iOS with the UIStoryboard class method storyboardWithName:bundle.



Watch Out!: Storyboards Are the Way to Go

iOS applications can still be built using XIB files if you uncheck Use Storyboard when creating a new project. I suspect Apple will eventually drop support for XIB files in iOS, so I recommend avoiding new non-storyboard projects.


The Anatomy of an Interface Builder File

What do XIB files and storyboard files look like in IB? Let’s start with a XIB file. Open the Hour 8 Projects folder and double-click the file MainMenu.xib to open Interface Builder and display a sample XIB file. The contents of the file are shown in the IB editor, as shown in Figure 8.2.

Image

Figure 8.2. An XIB file’s objects are represented by icons.

The objects represented within the interface are visible in the dock (the column along the left side of the Editor area). The icons are divided into a top portion (called the placeholder objects), and a bottom portion (called the interface objects). To make this a big clearer, click and drag the right side of the dock to show the Document Outline (or choose Editor, Show Document Outline). The Document Outline is a much easier to understand view of the objects in the XIB (or storyboard) file. From here on, that’s the view we show (see Figure 8.3).

Image

Figure 8.3. The Document Outline view within the Interface Builder editor.

Placeholder Objects

In this sample XIB file, three placeholder icons are visible: File’s Owner, First Responder, and Application. These are special icons used to represent unique objects in our application and these will be present in all XIB files that you work with.

File’s Owner: The File’s Owner icon denotes the object that loads the XIB file in your running application. This is the object that effectively instantiates all the other objects described in the XIB file. For example, you may have an interface defined in myInterface.xib, which is loaded by an object you’ve written called myInterfaceController. In this case, the File’s Owner would represent the myInterfaceController object. You learn more about the relationship between interfaces and code in Hour 9, “Connecting a GUI to Code.”

First Responder: The First Responder icon denotes the object currently in control and interacting with the user. A text field that the user is typing into, for example, is the First Responder until the user moves to another field or control.

Application: The Application icon denotes the shared Application object (NSApplication, a global singleton) within your XIB. This object provides the main event loop and manages windows and menus for your application.

Interface Objects

Below the placeholder objects are the interface objects. By default, a Main Menu object, which defines the contents of the menu bar, and a single Window object are included in the OS X Cocoa application template.


Did You Know?

For the OS X application template, you’ll also see two non-UI objects included with the interface objects. The Font Manager object handles application fonts, and the App Delegate object represents the application delegate class within your project.


Many objects are hierarchical in nature. This means that as you add objects to your interface, they will be contained within other objects—views within windows, buttons within views, and so on. You can use the disclosure arrow located to the left of any object to expand it in the Document Outline, as shown in Figure 8.4.

Image

Figure 8.4. Expand objects to view the other objects it contains.


By the Way

At their most basic level, all interface objects are subclasses of NSView (OS X) or UIView (iOS). A view is a rectangular region that can contain content and respond to user events. All the controls (buttons, fields, and so on) that you’ll add to a view are, in fact, subclasses of a view. This isn’t necessarily something you need to be worried about, except that you’ll be encountering documentation that refers to buttons and other interface elements referred to as subviews and the views that contain them as superviews.

Just keep in the back of your mind that pretty much everything you see on the screen can be considered a “view” and the terminology will seem a little less alien.


Working with the Object Icons

The Document Outline (and Interface Builder dock) show icons for objects in your application, but what good are they? Aside from presenting a nice list, do the icons provide any functionality?

Absolutely. The icons give you a visual means of referring to the objects they represent. You interact with the icons by dragging to and from them to create the connections that drive your application’s features.

Consider an onscreen control, such as a button, that needs to be able to trigger an action in your code. By dragging from the button to the File’s Owner icon, you can create a connection from the GUI element you’ve drawn to a method you’ve written in the object that loaded the XIB file.

We go through two hands-on examples in the next hour so that you can get a feel for how this works on both OS X and iOS projects.

The Storyboard Differences

Now that you’ve seen what a XIB file looks like, return to your Projects folder for this hour and open the file MainStoryboard.storyboard. This is the default storyboard file for the iOS Single View Application type. When loaded, the Interface Builder editor is a bit different, as shown in Figure 8.5, than it was with the XIB file.

Image

Figure 8.5. Storyboard files appear a bit differently in Interface Builder.

First, the icon dock isn’t available in storyboard files. This makes sense because the storyboard can grow to have many different scenes (more on this in Hour 10), and trying to interpret what was what would get seriously confusing. Second, there are only two placeholder icons, and they are displayed both in the Document Outline and in a bar underneath the iOS application view.

By default, any storyboard scene contains two objects:

First Responder: A placeholder, just like the First Responder in OS X XIB files.

View Controller: Represents the object that is responsible for handling your interface events. In a vanilla iOS application, this is just the ViewController class.

Unlike OS X XIB files where the objects that make up the interface sat outside of the noninterface objects, here the interface objects sit inside the View Controller object. Expand the View Controller object by clicking the disclosure arrow in front of its name. You will see a third object appear: View (visible in Figure 8.5). This is the view that will be controlled by the View Controller object. You build your interfaces within a view, as demonstrated by a completed storyboard in Figure 8.6.

Image

Figure 8.6. You build your interfaces in the view controller’s view.


Guided Structure

You should be seeing at this point that iOS development guides your application structure in a much more rigid manner than OS X development. In an OS X application, your interface can be handled by the class that loaded it, or by entirely separate classes that you instantiate in your XIB file. (We discuss adding arbitrary objects representing any class later this hour.) You can add as many windows as you want and, basically, create a complete mess if that’s your thing.

In iOS applications, it is certainly possible to create a mess, but the storyboard files are structured so that you must have a ViewController class that manages a view. You build your interface starting from the view, and if additional displays are necessary (read “multiple scenes”), they too will have a view controller and a view.


Creating User Interfaces

You’ve seen the default state of a OS X application interface and an iOS interface, but how do we go from that to an application interface that works? Figure 8.7 shows a simple functional application UI that you work with in the next hour.

Image

Figure 8.7. From nothing, to something.

In this section, we explore how interfaces are created with the Interface Builder editor. In other words, it’s time for the fun stuff.

If you haven’t already, open the MainMenu.xib file or MainStoryboard.storyboard file included in this hour’s Projects folder. Use the Document Outline to open select and display a window (or an iOS view) in the editor.

The Object Library

Everything that you add to a view, from buttons and images to web content, comes from the Object Library. You can view the library by choosing View, Utilities, Show Object Library from the menu bar (Control+Option+Command+3). If it isn’t already visible, the Utility area of the Xcode interface opens, and Object Library is displayed in the lower-right. Make sure that the Objects item is selected in the pop-up menu at the top of the library so that all available options are visible.


Watch Out!: Libraries, Libraries, Everywhere!

Xcode has more than one library. The Object Library contains the UI elements you’ll be adding in Interface Builder, but there are also File Template, Code Snippet, and Media libraries that you can activate by clicking the icons immediately above the library area.

If you find yourself staring at a library that doesn’t seem to show what you’re expecting, click the cube icon above the library, or reselect the object library from the menu to make sure you’re in the right place.


When you click and hover over an element in the library, a popover is displayed with a description of how the object can be used in the interface, as shown in Figure 8.8. This provides a convenient way of exploring your UI options without having to open the Xcode documentation.

Image

Figure 8.8. Learn about the objects you can add to your XIB or storyboard file.


Did You Know?

Using view buttons at the top of the library, you can switch between list and icon views of the available objects. You can also focus in on specific UI elements using the pop-up menu above the library listing. If you know the name of an object but can’t locate it in the list, use the Filter field at the bottom of the library to quickly find it, or the pop-up menu at the top of the list to limit what is shown to specific subset of objects.


Adding and Removing UI Objects

To add an object to a view, click and drag from the library to the view. For example, find the label object in the Object Library and drag it into the center of the OS X window’s views or into the iOS storyboard scene’s view. The label should appear in your UI and read Label. Double-click the label and type Hello World. The text will update, as shown in Figure 8.9, just as you would expect.

Image

Figure 8.9. Add objects by dragging them into your OS X or iOS views.

With that simple action, you’ve written a Hello World application. Try dragging other objects from the Object Library into the view (buttons, text fields, and so on). With few exceptions, the objects should appear and behave just the way you expect.

To remove an object from the view, click to select it, and then press the Delete key. If you find it difficult to target an object directly in the user interface, select it from the Document Outline instead.


By the Way

In storyboard files, the +/- magnifying glasses in the lower right of the Editor area will zoom in and out on your interface for fine-tuning a scene. This proves useful when creating storyboards with multiple scenes. Unfortunately, you cannot edit a scene when zoomed out, so Apple provides the = button to quickly jump back and forth between a 100% view and your last chosen zoom setting.

OS X XIB files get an entirely different menu in the lower-right corner for arranging and managing the UI spacing and sizing. More on that later.



Did You Know?

Not all objects are UI objects. Some objects (controllers for other objects, for instance) have no onscreen representation. These objects are dragged from the Object Library directly into the Document Outline area, where they are added to a scene (storyboard) or object list (XIB).


Working with the IB Layout Tools

Instead of relying on your visual acuity to position objects in a view, Apple has included some useful tools for fine-tuning your layout. If you’ve ever used a drawing program like OmniGraffle or Adobe Illustrator, you’ll find many of these familiar.

Guides

As you drag objects in a view, you’ll notice guides appearing to help with the layout. These blue dotted lines are displayed to align objects along the margins of the view, to the centers of other objects in the view, and to the baseline of the fonts used in the labels and object titles, as shown in Figure 8.10.

Image

Figure 8.10. Use the guides to help position your objects.

As an added bonus, guides automatically appear to indicate the approximate spacing requirements of Apple interface guidelines. If you’re not sure why it is showing you a particular margin guide, it is likely that your object is in a position that Interface Builder considers “appropriate” for something of that type and size.


Did You Know?

You can manually add your own guides by selecting a view and choosing Editor, Add Horizontal Guide or by choosing Editor, Add Vertical Guide.


Selection Handles

In addition to the layout guides, most objects include selection handles to stretch an object either horizontally, vertically, or both. Using the small boxes that appear alongside an object when it is selected, just click and drag to change its size, as demonstrated in Figure 8.11.

Image

Figure 8.11. Use the handles to resize your objects.

Some objects constrain how you can resize them; this preserves a level of consistency within the application interfaces.


Did You Know?

OS X windows work a bit differently. To resize windows, use the gray border that Xcode adds around their onscreen display in the Interface Builder editor. Also, be aware that clicking the X in the upper-left corner of the window border closes it, but the Window object is still part of the XIB file. Double-clicking it in the document outline opens it again.


Alignment

To quickly align several objects within a view, select them by clicking and dragging a selection rectangle around them or by holding down the Shift key, and then choose Editor, Align and an appropriate alignment type from the menu.

For example, try dragging several buttons into your view, placing them in a variety of different positions. To align them based on their horizontal center (a line that runs vertically through each button’s center), select the buttons, and then choose Editor, Align, Horizontal Centers. Figure 8.12 shows the before and after results.

Image

Figure 8.12. Use the Align menu to quickly align a group of items to an edge or center.

OS X developers can get even faster access to alignment features using the Align pop-up menu in the lower-right corner of the editor.


Did You Know?

To fine-tune an object’s position within a view, select it, and then use the arrow keys to position it left, right, up, or down, 1 pixel at a time.


The Size Inspector

Another tool that you may want to use for controlling your layout is the Size Inspector. Interface Builder has a number of “inspectors” for examining the attributes of an object. As the name implies, the Size Inspector provides information about sizes, but also position and alignment. To open the Size Inspector, first select the object (or objects) that you want to work with, and then click the ruler icon at the top of the Utility area in Xcode. Alternatively, choose View, Utilities, Show Size Inspector or press Option+Command+5. Figure 8.13 shows the OS X version of the inspector.

Image

Figure 8.13. The Size Inspector enables you to adjust the size and position of one or more objects.

At the top of the inspector is a Control section, which enables you to choose between different sizes of a given UI control. Next, in the View section, you can change the size and position of the object by changing the coordinates in the Height/Width and X/Y fields. You can also view the coordinates of a specific portion of an object by clicking one of the black dots in the size and grid to indicate where the reading should come from.


By the Way

Within the Size and Position settings, notice a drop-down menu where you can choose between Frame Rectangle and Layout Rectangle. These two settings are usually very similar, but there is a slight difference. The frame values represent the exact area an object occupies onscreen, whereas the layout values take into account spacing around the object.



By the Way

When an object is selected, press the Option button to quickly get a read on the distances (in view coordinates, starting at 0,0 in the upper left) between the edges of an object and the view it is within.


Auto Layout and Content Hugging and Compression

By default, OS X applications now enable a feature called Auto Layout. This makes it possible for application controls to dynamically adjust their sizing as their views change size (most often from a user resizing a window). We look at the Auto Layout features in a few minutes.

If you prefer to disable Auto Layout in your application and instead use the autosizing features available in iOS applications, open the File Inspector for the XIB file (Option+Command+1) and uncheck the Use Auto Layout check box, as shown in Figure 8.14.

Image

Figure 8.14. Disable Auto Layout to use the same autosizing features as iOS.

Autosizing

The autosizing settings of the Size Inspector determine how controls resize/reposition themselves when a window (OS X) changes sizes or a device (iOS) changes orientation.

This deceptively simple “square in a square” interface provides everything you need to tell Interface Builder where to anchor your controls and in which directions (horizontally or vertically) they can stretch.

To understand how this works, imagine that the inner square represents one of your interface elements and the outer square is the view that contains the element. The lines between the inner and outer square are the anchors. When clicked, they toggle between solid and dashed lines. Solid lines are anchors that are set. This means that those distances will be maintained when the interface changes size.

Image

Figure 8.15. The autosizing settings control anchor and size properties for any onscreen object.

Within the inner square are two double-headed arrows, representing horizontal and vertical resizing. Clicking these arrows toggles between solid and dashed lines. Solid arrows indicate that the item is allowed to resize horizontally, vertically, or both.

For example, to create a button that stays in the center of the screen and grows/shrinks proportionally when the view changes sizes, follow these steps using the MainStoryboard.storyboard file:

1. Add a button to the center of the view.

2. Open the Size Inspector (Option+Command+5).

3. Remove any existing anchors around the edges of the center box.

4. Click the horizontal arrowed line in the center of the box to enable horizontal resizing, as shown in Figure 8.16.

Image

Figure 8.16. Create a button that floats in the center of the screen and resizes horizontally when the view changes size.


Did You Know?

If you need a more “visual” means of understanding the autosizing controls, just look to the right of the two squares. The rectangle to the right shows an animated preview of what will happen to your control (represented as a red rectangle) when the view changes size around it. The easiest way to understand the relationship between anchors, resizing, and view size/orientation is to configure the anchors/resize arrows and then watch the preview to see the effect.


The Auto Layout System

While the guides, Size Inspector, and other tools are helpful for laying out interfaces—even interfaces that can adapt to view changes—OS X applications can take advantage of a new powerful tool for managing layouts: the Auto Layout system. Auto layouts are OS X only and are enabled by default on new projects. Review the previous section, “Auto Layout and Content Hugging and Compression,” for more information on enabling or disabling auto layouts.

Understanding Constraints

Auto Layout works by building a series of constraints for your onscreen objects. The constraints define distances between objects and how flexible these relationships are. For example, try adding a button to the window in MainMenu.xib; make sure it is located toward the top-left side of the view. Notice that parallel to the button in the object hierarchy a new Constraints entry shows up, as shown in Figure 8.17.

Image

Figure 8.17. The Constraints object represents the positioning relationships within a view.

Within the Constraints object are two constraints: horizontal space and vertical space constraint. The horizontal constraint states that the left side of the button will be a certain number of points from the left edge of the view. The vertical constraint is the distance from the top of the view to the top of the button. What constraints are added depend on where the object is in relation to its containing view.

Constraints, however, are more than just entries that tie an object to the view it is within. They can be flexible, ensuring that an object maintains at least or at most a certain distance from another object, or even that two objects, when resized, maintain the same distance between one another.

Constraints that set a specific size or distance between objects are called pinning. The flexibility (or inflexibility of a constraint) is managed by configuring a relationship.


Did You Know?

Alignment of objects is also listed as a constraint, but is managed using the alignment tools you’ve already seen.


Setting Constraints and Relationships

Let’s look at an example of two buttons that are located a set distance (150 points) from either side of a window that will grow farther apart or closer together when the window is resized but won’t allow themselves to be any closer than 75 points apart.

To do this, begin by adding your buttons:

1. If you already have a push button added to a window in the MainWindow.xib file, you’re in good shape. If not, add one now. Position the button along the left side of the window.

2. Repeat this for a second button, positioning it along the right side of the window. Use the guides to align the baseline of each button’s label.

Xcode should automatically create constraints for the first button that tie it to the top of the left side and top of the view (or center of the view, if centered vertically). The second button will be tied to the baseline of the first button and the right side of the view, as shown in Figure 8.18.

Image

Figure 8.18. Four constraints should exist for the two buttons.

Now, adjust the two buttons so that they are located 150 points from the sides of the view:

1. Select the Horizontal Space constraint for the first button within the Constraints object in Document Outline.

2. Open the Attributes Inspector (Option+Command+4). Here you can define the constraint relationship.

Because we want the button to be exactly 150 points from the side of the view, the Constant field is set to 150, and the Relation pop-up is set to Equal, as shown in Figure 8.19. The other settings are left at their defaults.

Image

Figure 8.19. Set constraints to tie your objects to the view.

3. Repeat this set for the other button’s horizontal constraint. They will now be located exactly 150 points from the edges of the view.

The final thing you must do is tell the interface that no matter how it is resized, the buttons should never be closer together than 75 points. This involves creating and configuring a new relationship:

1. Select both buttons. (Click to select one and then hold Shift and click to select the other.)

2. Use the middle icon of the layout button at the bottom of the editor (or the Editor, Pin menu) to choose Horizontal Spacing. This creates a constraint that manages the spacing between the two buttons.

3. Select this constraint and then open the Attributes Inspector (Option+Command+4). This time set the relation to Greater Than or Equal, meaning the horizontal spacing will always be equal to or larger than the provided value.

4. Set the constant to 75, meaning the buttons will be at least 75 points apart at all times, as shown in Figure 8.20.

Image

Figure 8.20. Create a flexible constraint.

You can now test your constraints by resizing the window in the Interface Builder editor. Notice that the buttons go apart as expected, but limit the window from shrinking to a size that would violate the 75-point horizontal-spacing constraint.


Did You Know?

When defining the constraint relationships in the Attributes Inspector, you may have noticed a Priority slider and a Standard check box. The Priority slider determines how “strong” the constraint relationship is. There may, for example, be instances when multiple constraints must be evaluated against one another.



Did You Know?

The priority setting determines the importance of any given constraint. A value of 1000 is a constraint that is required. If you move the Constraint slider, Xcode shows a description of what to expect at a given constraint priority.

The Standard check box lets Xcode use its internal database of spacing to set the recommended space between two objects. This, in many cases, is preferred because it ensures a consistent interface.


Content Hugging and Content Compression Resistance

Earlier in the hour, you learned that the Content Hugging and Compression Resistance settings in the Size Inspector (refer to Figure 8.14) are related to Auto Layout. So, where do these tie in?

When inspecting an object that is within an Auto Layout XIB, these settings control how closely the sides of an object “hug” the content in the object and how much the content can be compressed or clipped. A button, for example, can expand horizontally (so horizontal hugging is a low priority) but shouldn’t grow vertically (making vertical hugging a very high priority). Similarly, the content (the button label) should not be compressed or clipped at all, so the content compression resistance settings for both horizontal and vertical compression should be very high priority.

You will not often need to adjust these settings beyond their defaults, which Interface Builder adds for you.


Wait... There’s More

There is far more to the Auto Layout system than can be described in an hour. Be sure to explore the Pin menu to see the different types of constraints that you can put in place. Width/height constraints enforce a given width or height on an object. Equal width/height constraints ensure multiple objects maintain an equal width or height. The leading/trailing space pinnings tie the left side of an object to the left side of its parent view (leading), or the right side of an object to the right side of its parent view (trailing).

Review Apple’s documentation, starting with “Cocoa Auto Layout Guide,” for more information.


Customizing Interface Appearance

How your interface appears to the end user isn’t just a combination of control sizes and positions. For many kinds of objects, there are literally dozens of different attributes that you can adjust. Although you could certainly configure things such as colors and fonts in your code, it is easier to just use the tools included in the Interface Builder editor.

Using the Attributes Inspector

The most common place you’ll tweak the way your interface objects appear is through the Attributes Inspector, available by clicking the slider icon at the top of the Utility area. You can also choose View, Utilities, Show Attributes Inspector (Option+Command+4) if the Utility area isn’t currently visible. Let’s run through a quick example to see how this works.

Open the MainStoryboard.storyboard file and add a label to your view. Select the label and then open the Attributes Inspector, shown in Figure 8.21.

Image

Figure 8.21. To change how an object looks and behaves, select it, and then open the Attributes Inspector.

The top portion of the Attributes Inspector contains attributes for the specific object. In the case of the text object, this includes settings such as font, size, color, and alignment—everything you’d expect to find for editing text. Try changing a few of the settings and see what happens to the label. You should be able to easily set its size, color, and font.

In the lower portion of the inspector are additional inherited attributes. Remember that onscreen elements are a subclass of a view? This means that many of the standard view attributes are also available for the object and for your tinkering enjoyment (and, for OS X, NSControl attributes). In many cases, you’ll want to leave these alone, but settings such as background and transparency can come in handy.


By the Way

OS X UI objects behave a bit differently from most iOS objects. When you are working with iOS objects in the Document Outline, they are represented as just a single configurable object. A button is a button, end of story. OS X objects, however, are very often a hierarchy of objects, each with its own attributes to be configured. A table view, for example, expands to show objects for each column. You might use the top-level table view object to choose whether column headings are visible, but then drill down to a column to choose whether clicking its heading results in the table contents sorting.



Did You Know?

The attributes you change in Interface Builder are simply properties of the object’s class. To help identify what an attribute does, use the documentation tool in Xcode to look up the object’s class and review the descriptions of its properties. Don’t spend your time trying to memorize these—there’s no point in filling your head with this minutia.


Simulating the Interface

At any point in time during the construction of your interface, you can test the layout without having to build the full project. To test the interface, choose Editor, Simulate Document. After a few seconds, the interface appears in the Cocoa Simulator. You can resize windows, click controls, and generally give your interface design a workout.


Watch Out!: Less Than Meets the Eye

When you use the Simulate Document command, only the interface code is being run. Nothing that you may have written in the code editor is included. Therefore, you can simulate interfaces even before you’ve written a single line of supporting code or if your code has errors. However, it also means that if your code modifies the display in any way, you won’t see those changes onscreen.


Unfortunately, you lose the ability to simulate the interface with iOS storyboards. If you’re developing an iOS application, you must run the application code if you want to see an interface. You learn more about the iOS simulation tool and its role in testing in Hour 11, “Building and Executing Applications.” That said, one of the biggest reasons to test an iOS interface is to see how it performs under rotation events. You can do this in the storyboard by selecting the View Controller object and opening the Attributes Inspector (Option+Command+4). Use the Orientation setting under Simulated Metrics to force a scene to be visible in Landscape mode, as shown in Figure 8.22. This does take into account all settings made within the Size Inspector and re-lays out the display as needed.

Image

Figure 8.22. Simulate Landscape iOS views without leaving the Interface Builder editor.


Did You Know?

When you simulate an OS X Cocoa application interface, it starts the Cocoa Simulator. This is nothing more than a XIB simulator and has nothing in common with the iOS simulator that you’ll learn about in Hour 11. The iOS simulator runs your full iOS apps without an iOS device present.


Setting Object Identities

As we finish this introduction to Interface Builder, we would be remiss if we didn’t introduce one more feature: the Identity Inspector. As you drag objects into the interface, you’re creating instances of classes that already exist (buttons, labels, and so on). Often, however, you’ll build custom classes that also need to be referenced in Interface Builder. In these cases, you need to help Interface Builder out by identifying the subclass it should use.

For example, suppose we create a subclass of the standard button class that we name ourFancyButtonClass. We might drag a button into Interface Builder to represent our fancy button, but when the XIB or storyboard file loads, it just creates the same old UIButton.

To fix the problem, we select the button we’ve added to the view, open the Identity Inspector by choosing Tools, Identity Inspector (Option+Command+3), and then use the drop-down menu/field to enter the class that we really want instantiated at runtime (see Figure 8.23).

Image

Figure 8.23. If you’re using a custom class, you need to manually set the identity of your objects in Interface Builder.


By the Way

You’ll use this often to set the class that implements an iOS scene’s view controller. You use the Document Outline to select the View Controller object in the scene, then within the Identity Inspector, set the custom class to the name of the class in your project that implements your view controller behavior.



Did You Know?

Use the Identity Inspector’s Label field to set a custom label that will be used in the display of the object in the Document Outline. For complex interfaces, this can help you tell dozens of similarly named objects from one another.


Adding Custom Objects to Interface Builder

To add an instance of an entirely custom/arbitrary object, search the Object Library for the Object item, as shown in Figure 8.24. You can drag this into your storyboard or XIB file Document Outline to instantiate any object you want.

Image

Figure 8.24. The Object item can represent any class instance you want.

Once this is visible in the Document Outline, open the Identity Inspector (Option+Command+3), type or choose the class in your application that this object should be an instance of, exactly as you saw in Figure 8.23.

When adding objects for your custom classes to the Document Outline, be sure to choose the objects that best represent your class. The generic “object” shown in Figure 8.24 can represent anything, but provides the fewest features to the rest of the objects in Interface Builder. A View Controller object, for example, would be a better representation of a custom subclass of NSViewController (OS X) or UIViewController (iOS) and would be your best choice for representing a custom view controller.


Inspectors Here, There, and Everywhere!

Several other inspectors that relate to the objects you use in Interface Builder have not been discussed this hour. The Connections Inspector helps connect interfaces to code and is the focus of the next hour. The Bindings Inspector enables you to connect OS X (not iOS) interfaces directly to data and is the topic of Hour 17, “Attaching Big Data: Using Core Data in Your Applications.”

Unfortunately, the View Effects Inspector, which enables you to apply visual effects to a view, is beyond the scope of this book. You can learn more about the View Effects Inspector in the Xcode document “Interface Builder User Guide” in the section “Attaching Graphical Effects in Mac OS X.”


Summary

This hour covered Interface Builder and the tools it provides for building rich graphical interfaces for your applications. You learned how to navigate the IB editor window and access the interface objects from the Object Library. Using the various inspector tools within Interface Builder, you reviewed how to customize the look and feel of the onscreen controls and their layout.

There are some significant differences to how XIB and storyboard documents look in Interface Builder, but the basic process for editing and managing the documents is the same. Hour 9 shows how these interfaces, be they iOS or OS X, are connected back to code; and Hour 10 focuses on what makes storyboards truly unique and powerful.

Q&A

Q. Why do I keep seeing things referred to as NIB files?

A. The origins of Interface Builder trace back to the NeXT Computer, which made use of NIB files. These files, in fact, still bore the same name when Mac OS X was released. In recent years, however, Apple has renamed the files to have the XIB extension—unfortunately, habits (and documentation) rarely change, so they are still commonly called NIB files.

Q. Some of the objects in the Interface Builder Library cannot be added to my view. What gives?

A. Not all of the library objects are interface objects. Some represent objects that provide functionality to your application. These are added directly to the object list in the Document Outline.

Q. I’m using control XYZ on OS X but don’t see it on iOS.

A. Although there are many similarities between OS X and iOS development, many differences also exist. The UI controls, while performing similar functions across both platforms, are often implemented by very different objects. Search for generic terms instead of using specific class names.

Workshop

Quiz

1. Simulating an interface from IB also compiles the project’s code in Xcode. True or false?

2. What is a constraint relationship?

3. It is impossible to represent custom classes in Interface Builder. Yes or no?

Answers

1. False. Simulating the interface does not use the project code at all. As a result, the interface will not perform any coded logic that may be assigned.

2. A constraint relationship defines how an interface element relates to another element, such as a distance that should be maintained between them.

3. No. Using the Identity Inspector, you can set the class that should be instantiated for any object represented in Interface Builder.

Activities

1. Practice using the interface layout tools on the MainMenu.xib file or MainStoryboard.storyboard file. Add each available interface object to your view, and then review the Attributes Inspector for that object. If an attribute doesn’t make sense, remember that you can review documentation for the class to identify the role of each of its properties.

2. Read the Xcode “Interface Builder User Guide.” This document can be helpful to get a sense for where various features and settings are tucked within the myriad of interface builder menus and inspectors.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.158.21