You are on page 1of 52

Xcode Quick Start Guide

Contents

About Xcode 4
At a Glance 4 The Workspace Window Manages Projects 4 Contextual Help Provides Focused Assistance 5 How to Use This Document 5 See Also 6

Tutorial: Using Xcode to Write Hello, World! for Mac OS X 7


Create the Cocoa Application Project 8 Create the NSView Subclass 10 Design the User Interface 13 Write the Code 20 Run the Application 25 View Task and Session Logs 27

Tutorial: Designing a User Interface with Interface Builder 29


Use Interface Builder To Create the User Interface 30 Creating the Viewer 30 Adding the Pause/Play Button 38 Adding the Load Button 41 Connecting Actions and Outlets 43 Add Implementation Code to Complete the Application 46 Verify the Code Added by Interface Builder 46 Add Implementation Code 48 Test the Load Button 48 Whats Next? 50

Document Revision History 51

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

Figures and Listings

Tutorial: Using Xcode to Write Hello, World! for Mac OS X 7


Figure 1-1 Figure 1-2 Figure 1-3 Figure 1-4 Figure 1-5 Figure 1-6 Figure 1-7 Listing 1-1 Listing 1-2 The Hello application in action 7 The Interface Builder dock and canvas 14 Interface Builder dock in list view 14 The utility area in the workspace window 16 The source editor 20 Hello application stopped at a breakpoint 26 The log viewer in the workspace window 28 Initial implementation of the HelloView class 21 Implementation of the drawRect: method 24

Tutorial: Designing a User Interface with Interface Builder 29


Figure 2-1 Listing 2-1 Listing 2-2 The QCDemo window 30 The QCDemoAppDelegate header file 46 The QCDemoAppDelegate implementation file 47

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

About Xcode

Xcode is a highly customizable integrated development environment (IDE) with many features for creating an efficient and effective working environment.

At a Glance
Xcode facilitates the development of software products of all sizes, from iPod games to enterprise solutions. The Xcode application is the main component of the Xcode toolset. It groups most of the tools you need to develop software in a streamlined and interactive user interface.

The Workspace Window Manages Projects


The workspace window is the control center for one or more projects.

Toolbar

Project navigator

Source editor

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

About Xcode How to Use This Document

A Project Groups the Resources Needed to Develop Products


A project contains the elements you use to design and build one or more productsincluding source files, user-interface designs, sounds, images, and links to supporting frameworks and libraries. The most user-visible type of software product you can create with Xcode is an application, but thats not the only kind of product you can create. You can also develop Automator actions, command-line tools, frameworks, plug-ins, kernel extensions, and other types of products.

The Project Navigator is Where You Organize the Main Components of Your Projects
The project navigator lets you find project components quickly. For example, you can add and modify the groups in the project navigator to reduce clutter.

The Source Editor is Where You Write Code


The source editor has many features to make your job easier, including automatic formatting, code completion and correction, and in-line debugging.

The Toolbar Contains Controls for Common Tasks


The workspace window toolbar provides quick access to project configuration and management tools that you use frequently. For example, you can analyze code, run applications, view the progress of various activities, and configure the workspace window to fit the task you are performing.

Contextual Help Provides Focused Assistance


Xcode provides help articles tailored to the task youre performing. The shortcut menu of user-interface elements contains a Help item that provides essential information about the element and the tasks you can perform with it.

How to Use This Document


Follow "Tutorial: Using Xcode to Write Hello, World! for Mac OS X" (page 7) to get an introduction to the source editor and Interface Builder, the main Xcode facilities you use to develop applications. Follow "Tutorial: Designing a User Interface with Interface Builder" (page 29) to learn how Interface Builder lets you to graphically create user interfaces using standard user-interface elements.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

About Xcode See Also

See Also

Xcode 4 User Guide provides information about the essential tasks you perform as you develop your products.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

Tutorial: Using Xcode to Write Hello, World! for Mac OS X


This short tutorial shows how to create a project for a Mac application that prints text in a window. Working through this tutorial, you get acquainted with the software-creation workflow in Xcode: creating the project, designing the user interface, writing code, and running the application. You also learn how to fix code errors Xcode detects as you write the code, and you get an introduction to the Xcode debugging facilities. Hello is a simple application. When the user launches it, a window appears, displaying the text Hello, World!, similar to the window shown in Figure 1-1.
Figure 1-1 The Hello application in action

Under the hood, the user interface consists of a window that contains a view. Views know how to display data. These objects have a built-in method through which Cocoa manages drawing into the view. You need to provide the code that draws the Hello, World! message. In this tutorial you use Objective-C and the Cocoa framework to create a view and implement the drawing routine. You dont need to be familiar with Cocoa or Objective-C to complete this tutorial, but you should be familiar with programming in some language, preferably a C-based or object-oriented language. To perform the tutorial you must have Xcode installed on your Mac. Visit developer.apple.com to download Xcode. In this tutorial you:

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Create the Cocoa Application Project

Create the Hello project Add a source file to the project Lay out the user interface of the Hello window Write the code that displays the message on the Hello window Build and run the Hello application View the messages produced by building the Hello application

Create the Cocoa Application Project


Xcode provides project templates that generate several types of products, including applications, frameworks, plug-ins, and static libraries. To create the Cocoa application project on which the Hello application is based:
1.

Launch Xcode, located in the Applications folder of your Xcode installation. Ensure that there are no Xcode windows open.

2. 3.

Choose File > New > New Project. In the Mac OS X group, select Application, then select Cocoa Application template, and click Next.

4.

Specify the options for the project, and click Next:

Product Name: Hello.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Create the Cocoa Application Project

Company Identifier: com.mycompany. App Store Category: None. Create Document-Based Application: not selected, which disallows entry into the Document Class and Document Extension fields. Use Core Data: not selected. Include Unit Tests: not selected.

5.

In the dialog that appears, navigate to the file-system location where you want to place the project directory (for example, the Desktop), ensure the Create local git repository for this project option is not selected, and click Create.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Create the NSView Subclass

After creating the project directory in your file system, Xcode opens it in a workspace window.

The project contents appear in a pane (known as the project navigator ) on the left side of the window. The first item in the group represents the project, and its named after the product name you specified when you created the project. Xcode groups the components of the Hello project in three groups:

Hello: Contains the files that make up the project. These files include source code files and a user-interface file. This group also contains a subgroup, named Supporting Files, that contains files used in supporting tasks. You dont modify these files in this tutorial. Frameworks: Identifies frameworks or libraries your code relies on for its functionality; for example, the Cocoa framework. Products: Contains the products your project produces, such as an application.

Create the NSView Subclass


Now you add a class to the project through which the Hello application displays its message. Cocoa draws in objects known as views . The essential functionality of a view is implemented by the NSView class, which defines the basic drawing, event handling, and printing architecture of an application. You typically dont interact with the NSView class directly. Instead you create an NSView subclass, and override the methods whose behavior you need to customize. Cocoa automatically invokes these methods. To create the NSView subclass in the Hello project:
1.

Choose File > New > New File.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

10

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Create the NSView Subclass

Note If the New File command is dimmed in the New menu, ensure that the Hello workspace window has the focus (that it is the frontmost window) by clicking inside it. The commands Xcode makes available in the menu bar depend on the window that has the focus. Many project-related commands are not available when a window other than a workspace window has the focus.

2.

In the Mac OS X group, select Cocoa, then select the Objective-C class template, and click Next.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

11

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Create the NSView Subclass

3.

Specify that the new file is a subclass of NSView, and click Next:

4.

In the dialog that appears, enter HelloView.m as the filename, choose the Hello group (which uses a yellow folder icon) from the Group pop-up menu, and click Save.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

12

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Design the User Interface

Xcode adds the header and implementation files for the HelloView class to the project. They are listed in the project navigator.

Design the User Interface


Interface Builder is the graphical user-interface editor used to edit the documents, called nib files , that define an applications user interface. You directly lay out and manipulate user-interface objects (known as controls ) to construct your user interfaces. Add an instance of the HelloView class to the Hello application window:
1.

In the project navigator, select the MainMenu.xib file. Xcode opens the file in Interface Builder, the Xcode user-interface editor.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

13

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Design the User Interface

This editor has two major areas, highlighted in Figure 1-2: the dock (on the left) and the canvas (on the right). The dock displays the objects in the nib file. The canvas is where you lay out your applications user interface using the objects in the nib file.
Figure 1-2

The Interface Builder dock and canvas

2.

If the canvas shows the Hello menu bar object, as the previous screenshot does, click its close box (x) to remove it from the canvas. If the dock appears in outline view (Figure 1-3) instead of icon view (Figure 1-2), click the highlighted button to change it to icon view.
Figure 1-3

3.

Interface Builder dock in list view

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

14

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Design the User Interface

4.

Click the Window - Hello item in the dock to display the Hello window in the canvas.

5.

Choose View > Navigators > Hide Navigator to narrow the focus of the workspace (you wont be navigating the project in the next few steps). Choose View > Utilities > Show Utilities.

6.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

15

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Design the User Interface

The utility area (Figure 1-4) contains two panes: the inspector pane (top) and the library pane (bottom). The library pane contains libraries for file templates, code snippets, objects, and media.
Figure 1-4

The utility area in the workspace window

7.

Display the Object library by choosing View > Utilities > Object Library. Make the library pane taller by dragging its selector bar up. (This also makes the inspector pane shorter.)

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

16

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Design the User Interface

8.

From the Object Library pop-up menu, choose Cocoa > Layout Views.

9.

Drag the Custom View object from the library to the Hello window in the canvas.

Youve created an instance of the NSView class and added it to the window.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

17

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Design the User Interface

10. Resize the newly added view by dragging its sides to the Hello windows borders, so that it occupies the

entire content area of the Hello window.

11. Choose View > Utilities > Identity Inspector.

The Identity inspector lets you specify details about user-interface elements that identify them to users of your application (tooltips, also called help tags ) and to the system (class, runtime attributes, object ID, and so on).

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

18

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Design the User Interface

12. In the Identity inspector, choose HelloView from the Class pop-up menu in the Custom Class section.

Notice that the label for the view changes from Custom View to HelloView.
13. Choose View > Utilities > Size Inspector.

In the Size inspector you can enter precise values for positioning and sizing controls. The Autosizing area lets you specify how (and whether) controls change size and position as the enclosing window changes size. (You can also change the layout by moving and resizing controls on the Interface Builder canvas.)
14. In the Autosizing area, click the vertical and horizontal dotted lines in the inner square.

Notice that the dotted lines change to solid ones. Solid lines in the inner square indicate the directions the view resizes automatically. In this case, the view resizes vertically and horizontally when the user changes the window size. The example animation to the right of the Autosizing area provides a simulation of the new sizing behavior.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

19

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Write the Code

There is much more to Interface Builder than youve seen here. When you develop more advanced applications, you use the inspectors to set connections to associate the code you write to interact with user-interface objects.

Write the Code


You can view and edit a source file in the workspace window by selecting the file in the project navigator, which opens it in the source editor, shown in Figure 1-5.
Figure 1-5
Jump bar

The source editor

Gutter

Focus ribbon

The gutter displays line numbers (when the Line numbers option in Text Editing preferences is selected; see Text Editing Preferences Help ) and the location of breakpoints, errors, and warnings in the file. The focus ribbon helps you to concentrate your attention on your code by:

Identifying the scope of a block of code Allowing you to hide blocks of code

The Jump bar allows you to:

View related files Move backward and forward through the set of project files youve viewed Jump to another location within the current file or to another file in the project

To enter the source code for the Hello application:

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

20

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Write the Code

1. 2. 3.

Choose View > Navigators > Project. Choose View > Utilities > Hide Utilities. In the project navigator, select HelloView.m to open it in the source editor. Listing 1-1 shows the initial implementation of the HelloView class.
Initial implementation of the HelloView class

Listing 1-1

#import "HelloView.h" @implementation HelloView

- (id)initWithFrame:(NSRect)frame { if ((self = [super initWithFrame:frame])) { // Initialization code here. } return self; }

- (void)dealloc { // Clean-up code here. [super dealloc]; }

- (void)drawRect:(NSRect)dirtyRect { // Drawing code here. } @end

4.

Insert this code line in the body of the drawRect: method:


NSString *hello = "Hello, World!";

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

21

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Write the Code

Notice that the gutter shows a warning icon. This means that Xcode has found a problem in the code you just typed. To get information about the problem, click the warning icon. Xcode describes the problem and offers a solution.

Double-click Insert "@" (or press Return) to convert the C string into an Objective-C string object. Youve just taken advantage of Live Issues (in-line issue detection and diagnosis) and Fix-it (automatic issue correction). The fixed code line should look like this:
NSString *hello = @"Hello, World!";

This code line creates the string that the Hello application draws into the view. Fix-it detects another problem: The hello variable is unused in the drawRect: method. Thats why theres still a warning icon in the gutter. Youll fix that problem shortly.
5.

Type this text below the code line you added in the previous step:
NSPoint point = NSMake

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

22

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Write the Code

As you type the name of a symbol, Xcode suggests completions to what youre typing.

This is code completion. You specify whether Xcode provides completions as you type in Text Editing preferences. Because Xcode sees that youre assigning the functions return value to a variable of type NSPoint, Xcode selects the NSMakePoint completion in the completion list. Press Return to choose that completion. Xcode highlights the first parameter in the completion.
6.

Type 15, press Tab, and type 75. Add a semicolon to the end of the line. The code line should look like this:
NSPoint point = NSMakePoint(15, 75);

This call creates a point at the specified coordinates. This point is the origin for drawing the message.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

23

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Write the Code

7.

Place the cursor on the NSMakePoint function name, and choose Help > Quick Help for Selected Item.

Quick Help provides a summary of the API reference for the selected symbol. From the Quick Help window you can access the rest of the developer library to get in-depth information about the symbol. Tip You can also hold down Option while moving the pointer over your code. When you put the pointer over a symbol, Xcode underlines the symbol. Click the symbol while holding down Option to display the Quick Help window.

8.

Complete the implementation of the drawRect: method so that it looks like Listing 1-2.
Implementation of the drawRect: method

Listing 1-2

- (void)drawRect:(NSRect)dirtyRect { NSString *hello = @"Hello, World!"; NSPoint point = NSMakePoint(15, 75); NSMutableDictionary *font_attributes = [[NSMutableDictionary alloc] init]; NSFont *font = [NSFont fontWithName:@"Futura-MediumItalic" size:42]; [font_attributes setObject:font forKey:NSFontAttributeName];

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

24

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Run the Application

[hello drawAtPoint:point withAttributes:font_attributes];

[font_attributes release]; }

After typing the code, correct transcribing errors found by Fix-it (the code provided has no problems).
9.

Add a breakpoint to the drawRect: method. Add the breakpoint by clicking the gutter to the left of the code line with the assignment to the font variable. Although the drawRect: method has no problems, adding a breakpoint to it allows you to familiarize yourself with the Xcode debugging facilities when you run the Hello application.

Notice that adding the breakpoint automatically activates breakpoints for your projectthe Breakpoints toolbar button has a pushed-in appearance.

Run the Application


1.

Choose Product > Run to run the Hello application. The activity viewer (the LCD-like display in the workspace window toolbar) displays information about the tasks Xcode performs in response, which are to build the Hello application and to launch it in an interactive debug session.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

25

Tutorial: Using Xcode to Write Hello, World! for Mac OS X Run the Application

Figure 1-6 shows a debugging session using the debug navigator (on the left), the source editor (on the right), and the debug area (below the source editor) to get information about the running code.
Figure 1-6

Hello application stopped at a breakpoint

Notice that the source editor can display the values of variables within a scope. When you place the pointer over the hello variable, the source editor displays information about the variable in a datatip. The debug area contains the variables pane and the console pane. The variables pane shows information about the variables of the drawRect: method. The console pane shows your programs console output. You can also enter commands directly to the debugger in the console pane.
2.

Choose Product > Debug > Continue to continue execution of the Hello application.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

26

Tutorial: Using Xcode to Write Hello, World! for Mac OS X View Task and Session Logs

The window of the Hello application appears with the Hello, World! message displayed in its bottom-left corner.

3.

Choose Hello > Quit Hello or click the Stop toolbar button in the workspace window to stop the Hello application.

View Task and Session Logs


The log viewer (the Xcode session and task log-viewing facility) lets you examine details about tasks Xcode has performed, such as building and running your programs. When things dont go as smoothly as they should, you can use this facility to locate the cause of problems. But even if there are no problems, you can view a log of the activities Xcode performed in response to your execution of the Run command. To view details about these activities:
1. 2.

Choose View > Navigators > Log. In the log navigator, select the Build Hello task. Then click All and All Messages in the log viewer. The log viewer shows the operations it performed while executing the build task on the Hello target, whose product is the Hello application.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

27

Tutorial: Using Xcode to Write Hello, World! for Mac OS X View Task and Session Logs

Selecting an operation in the log viewer (Figure 1-7) reveals the transcript button on the right side of the operation. Click the transcript button to display details about the operation.
Figure 1-7

The log viewer in the workspace window

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

28

Tutorial: Designing a User Interface with Interface Builder


Interface Builder is a visual design editor thats integrated into Xcode. You use Interface Builder to create the user interfaces of your iOS and Mac OS X applications. Using the graphical environment of Interface Builder, you assemble windows, views, controls, menus, and other elements from a library of configurable objects. You arrange these items, set their attributes, establish connections between them, and then save them in a special type of resource file, called a nib file. A nib file stores your objects, including their configuration and layout information, in a format that at runtime can be used to create actual objects in your program. In this tutorial, youll use Interface Builder to create the user interface for a simple Mac OS X application, called QCDemo, for viewing Quartz Composer compositions. Quartz Composer is a development tool for processing and rendering graphical data. The visual programming environment of Quartz Composer lets you develop graphic processing modules, called compositions , without writing a single line of graphics code.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

29

Tutorial: Designing a User Interface with Interface Builder Use Interface Builder To Create the User Interface

Note To complete this tutorial, you need to have installed Mac OS X v10.6.6 or later and Xcode 4.0 or later.

Use Interface Builder To Create the User Interface


When youve completed this tutorial, the QCDemo window should look like Figure 2-1. The QCDemo window contains a view to display a composition, a button to load a new composition, and a button to toggle between play and pause.
Figure 2-1 The QCDemo window

As you create this user interface, youll explore some of the commonly-used features of Interface Builder. Its time to get started.

Creating the Viewer


The first task is to create a simple Quartz Composer viewer.
1.

Select a project template.


a. b.

Open the Xcode application and choose File > New > New Project. Under Mac OS X, select Application.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

30

Tutorial: Designing a User Interface with Interface Builder Use Interface Builder To Create the User Interface

c. d.

Select the Cocoa Application template. Click Next.

2.

Specify options for the new project.


a. b. c.

Name the product QCDemo. Specify your company identifier (or accept the default identifier). Make sure that no other options are set.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

31

Tutorial: Designing a User Interface with Interface Builder Use Interface Builder To Create the User Interface

d.

Click Next.

3.

Create the project.


a. b. c.

Select a location for the new project folder. Make sure that the Source Control option is not set. Click Create.

4.

Add the Quartz framework to the projects target.


a. b.

In the project navigator, select the QCDemo project. In the project editor, under Targets, select QCDemo.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

32

Tutorial: Designing a User Interface with Interface Builder Use Interface Builder To Create the User Interface

c.

In the Summary pane, under Linked Frameworks and Libraries, click the Add (+) button.

d.

Choose Quartz.framework from the list and click the Add button. (Tip: Type quartz into the text field to filter the list.)

5.

Add source code to include the Quartz framework header.


a. b. c.

In the project navigator, select the file QCDemoAppDelegate.h. In the source editor, find the line #import <Cocoa/Cocoa.h>. After this line, add the line #import <Quartz/Quartz.h>.

Youll make more changes to this file later in the tutorial.


6.

Open the Interface Builder document.


a.

In the project navigator, find the nib file MainMenu.xib.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

33

Tutorial: Designing a User Interface with Interface Builder Use Interface Builder To Create the User Interface

b. c.

Click MainMenu.xib to open the document in the Interface Builder editor pane. In the Xcode menu bar, choose View > Navigators > Hide Navigator to narrow the focus of the workspace. If the Interface Builder dock on the left does not look like the figure below, click the button in the lower left corner to switch the dock to outline view.

d.

7.

Set the size attributes of the QCDemo window.


a. b.

In the Xcode menu, choose View > Utilities > Size Inspector. In the outline view at the left side of the Interface Builder editor, select the window. Until you select it, the window does not appear on the Interface Builder canvas. In the Size inspector, set the windows width to 480 and height to 420. Press Return after entering the height. Select the Minimum Size option.

c.

d.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

34

Tutorial: Designing a User Interface with Interface Builder Use Interface Builder To Create the User Interface

e.

Make sure the minimum size is set to 480 x 420.

8.

Add a Quartz Composer view to the QCDemo window.


a.

Make sure the Object library is visible in the pane below the Size inspector. If not, choose View > Utilities > Object Library. Enter quartz composer in the search field at the bottom of the library. Drag the Quartz Composer view from the library to the QCDemo window.

b. c.

9.

Set the size attributes of the Quartz Composer view.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

35

Tutorial: Designing a User Interface with Interface Builder Use Interface Builder To Create the User Interface

a.

Make sure the Quartz Composer view is still selected (Window QCDemo > View > View in the outline view). There are several ways to select an object in Interface Builder. If an object is nested inside another object, you can select it in the outline view, the jump bar, or by clicking the object on the canvas. The jump bar is located just above the editor pane.

b. c. d.

In the Size inspector, ensure that Origin is set to the lower-left corner, as shown in the figure below. Ensure that the Show menu is set to Frame Rectangle. Set the views X position to 0 and Y position to 60.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

36

Tutorial: Designing a User Interface with Interface Builder Use Interface Builder To Create the User Interface

e.

Set the views width to 480 and height to 360. Be sure to press Return after entering the height.

f.

Set the views autosizing control as shown in the figure below. You set the autosizing behavior for this view by clicking every arrow and line in the control so that each changes from a dotted line to a solid line.

10. Select an initial composition for the Quartz Composer view. a. b.

In the Xcode menu bar, choose View > Utilities > Attributes Inspector. In the Attributes inspector, click the Load Composition button.

c.

Load the Quartz Composer composition at the following location inside the System folder:

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

37

Tutorial: Designing a User Interface with Interface Builder Use Interface Builder To Create the User Interface

/System/Library/Screen Savers/Shell.qtz

This composition is available as a screen saver in System Preferences.


d.

Select the Start Playing Automatically option.

11. Run a simulation of the QCDemo user interface.

Interface Builder includes a separate application called Cocoa Simulator. You can use Cocoa Simulator to preview your user interface as you work on it.
a. b.

Choose Editor > Simulate Document to start the simulation and display the composition. Try enlarging the QCDemo window and observe what happens to the composition. The composition is automatically resized because of the way you changed the autosizing behavior of the Quartz Composer view. Press Command-Q to quit the simulation.

c.

12. Build and run the QCDemo application. a. b. c. d.

Click the Run button at the left end of the Xcode toolbar. If youre asked whether you want to save documents before building, click Save. Verify that the application runs correctly by moving and resizing the window. Press Command-Q or click the Stop button to quit the application.

Adding the Pause/Play Button


The next task is to add a button that toggles the Quartz Composer view between pause and play.
1.

Add a push button to the user interface.


a. b. c.

Make sure the Object library is still visible. If not, choose View > Utilities > Object Library. In the library pane, type button in the search field. Drag a push button from the library to the open area at the bottom of the QCDemo window.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

38

Tutorial: Designing a User Interface with Interface Builder Use Interface Builder To Create the User Interface

d.

Use the horizontal and vertical guides to position the button in the lower-right corner of the window.

2.

Set the attributes of the push button.


a.

Verify that the button is selected. It should have a handle at either end.

If the button cell is selected instead of the button itself, you wont see the buttons handles. To select the button, click anywhere in the canvas outside of the button, then click the button again.
b. c.

Choose View > Utilities > Attributes Inspector. In the Attributes inspector, change the button type to Toggle.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

39

Tutorial: Designing a User Interface with Interface Builder Use Interface Builder To Create the User Interface

d.

Change the buttons title to Pause and set its alternate title to Play. Be sure to press Return after entering the alternate title.

3.

Set the autosizing behavior of the button.


a. b.

Choose View > Utilities > Size Inspector. In the Size inspector, set the buttons autosizing control as shown in the figure below. Tip: if you dont see the autosizing control, make sure youve selected the push button and not the button cell.

4.

Connect the button to the Quartz Composer views play: action. This action method is implemented for you in the QCView class. For more information about this class, see QCView Class Reference .
a. b. c.

In the outline view, select the Quartz Composer view. Choose View > Utilities > Connections Inspector. In the Connections inspector, find play: under Received Actions.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

40

Tutorial: Designing a User Interface with Interface Builder Use Interface Builder To Create the User Interface

d.

Drag from the circle at the right of the play: action to the Pause/Play button. Release the mouse button to complete the connection.

5.

Run a simulation of the QCDemo user interface.


a. b. c. d.

Choose Editor > Simulate Document to start the simulation. Try toggling the Pause/Play button to make sure it works as expected. Try enlarging the window to make sure the button stays in the corner where it belongs. Press Command-Q to quit the simulation.

Adding the Load Button


The next task is to add a button that allows the user to select and load another composition.
1.

Add a second push button to the user interface.


a.

Drag a push button from the Library pane to the open area at the bottom of the QCDemo window.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

41

Tutorial: Designing a User Interface with Interface Builder Use Interface Builder To Create the User Interface

b.

Use the horizontal and vertical guides to position the button in the lower-left corner of the window.

2.

Set the attributes of the push button.


a. b. c.

Verify that the button in the lower-left corner of the window is selected. In the Attributes inspector, make sure the buttons type is Momentary Push In. Set the buttons title to Load.

3.

In the Size inspector, set the buttons autosizing control as shown in the figure below.

4.

Run a simulation of the QCDemo user interface.


a. b. c. d.

Choose Editor > Simulate Document to start the simulation. Try enlarging the window to make sure the Load button stays in the corner where it belongs. Try clicking the Load button. The button should highlight when clicked. Press Command-Q to quit the simulation.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

42

Tutorial: Designing a User Interface with Interface Builder Use Interface Builder To Create the User Interface

Connecting Actions and Outlets


The objects in your user interface must communicate with each other and with your source code if your program is to interact with the user. To specify which messages are sent and received, you use Interface Builder to create connections. You already created an action connection between the Pause/Play button and the play: method in the Quartz Composer view. The nib file also contains an outlet connection between the main window and the QCDemoAppDelegate class. The next task is to create the necessary connections between two other user interface objects and the QCDemoAppDelegate class. You need to connect the Load button to a new action method that loads compositions. You also need to connect the Quartz Composer view to an outlet that the action method uses to do its work. When you create connections directly to the source code in a controller class, Interface Builder adds code to the class to support the connections. You only need to add the implementation for any action methods.
1.

Prepare the workspace window for the task at hand.


a. b.

Choose View > Utilities > Hide Utilities. Choose View > Editor > Assistant to open the Assistant editor. If the editor opens below the canvas, choose View > Assistant Layout > Assistant Editors on Right. Confirm that the Assistant editor displays the QCDemoAppDelegate.h file. If not, use the Assistant editors jump bar to display this file.

c.

2.

Add an outlet connection from the Quartz Composer view to the QCDemoAppDelegate class.
a.

Control-drag from the Quartz Composer view to below the property declaration in the QCDemoAppDelegate.h file.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

43

Tutorial: Designing a User Interface with Interface Builder Use Interface Builder To Create the User Interface

b.

In the dialog that appears, specify an outlet named qcView of class type QCView.

c.

Click Connect. Interface Builder creates the connection and inserts code into the QCDemoAppDelegate class. Interface Builder inserts the following line into QCDemoAppDelegate.h:
@property (assign) IBOutlet QCView *qcView;

At runtime, this property is set to the address of the Quartz Composer view. Later in this tutorial, you will add code to QCDemoAppDelegate.m that uses this property.
d.

Control-click the Quartz Composer view to display its connections window. This window is similar in appearance and function to the Connections inspector. Verify that you made an outlet connection by looking for the qcView entry under Referencing Outlets.

e.

f. 3.

Dismiss the connections window by clicking its close box.

Add an action connection from the Load button to the QCDemoAppDelegate class.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

44

Tutorial: Designing a User Interface with Interface Builder Use Interface Builder To Create the User Interface

a.

Control-drag from the Load button to below the property declarations in the QCDemoAppDelegate.h file.

b.

Change the connection type to Action and specify an action named loadComposition of type id.

c.

Click Connect. Interface Builder creates the connection and inserts code into the QCDemoAppDelegate class. For example, Interface Builder declares the new action method in QCDemoAppDelegate.h:
- (IBAction)loadComposition:(id)sender;

In addition, Interface Builder adds an empty definition of the action method to QCDemoAppDelegate.m. Youll add the necessary code to define this method in the next section.
d.

Control-click the Load button to display its connections window.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

45

Tutorial: Designing a User Interface with Interface Builder Add Implementation Code to Complete the Application

e.

Verify that you made an action connection by looking for the loadComposition: entry under Sent Actions.

f.

Dismiss the connections window by clicking its close box.

Add Implementation Code to Complete the Application


Your user interface is now complete. To have a working application, you need only to implement the action method that loads a composition.

Verify the Code Added by Interface Builder


The next task is to verify that Interface Builder added source code you need to implement the action and outlet connections you just made.
1.

Prepare the workspace window for the task at hand.


a. b.

Choose View > Editor > Standard. Choose View > Navigators > Project.

2.

In the project navigator, select the file QCDemoAppDelegate.h. The file should look like Listing 2-1 (Interface Builder added the highlighted lines).
The QCDemoAppDelegate header file

Listing 2-1

#import <Cocoa/Cocoa.h> #import <Quartz/Quartz.h>

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

46

Tutorial: Designing a User Interface with Interface Builder Add Implementation Code to Complete the Application

@interface QCDemoAppDelegate : NSObject <NSApplicationDelegate> { @private NSWindow *window; QCView *qcView; }

@property (assign) IBOutlet NSWindow *window; @property (assign) IBOutlet QCView *qcView; - (IBAction)loadComposition:(id)sender;

@end

3.

Now select the file QCDemoAppDelegate.m. The file should look like Listing 2-2 (Interface Builder added the highlighted lines).
The QCDemoAppDelegate implementation file

Listing 2-2

#import "QCDemoAppDelegate.h"

@implementation QCDemoAppDelegate

@synthesize window; @synthesize qcView;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { // Insert code here to initialize your application }

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

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

47

Tutorial: Designing a User Interface with Interface Builder Add Implementation Code to Complete the Application

Add Implementation Code


The final task is to add the code that loads a composition.
1. 2.

In the project navigator, select the file QCDemoAppDelegate.m. Add the following code between the braces in the loadComposition: method:
void (^handler)(NSInteger);

NSOpenPanel *panel = [NSOpenPanel openPanel];

[panel setAllowedFileTypes:[NSArray arrayWithObjects: @"qtz", nil]];

handler = ^(NSInteger result) { if (result == NSFileHandlingPanelOKButton) { NSString *filePath = [[[panel URLs] objectAtIndex:0] path]; if (![qcView loadCompositionFromFile:filePath]) { NSLog(@"Could not load composition"); } } };

[panel beginSheetModalForWindow:window completionHandler:handler];

Test the Load Button


1.

Build and run the QCDemo application.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

48

Tutorial: Designing a User Interface with Interface Builder Add Implementation Code to Complete the Application

a.

Click Run. If youre asked whether you want to save documents before building, click Save.

b.

Click Load. An Open dialog appears.

c.

Use the dialog to load another Quartz Composer composition. For example, load:
/System/Library/Screen Savers/Arabesque.qtz

2.

Press Command-Q or click the Stop button to quit the application.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

49

Tutorial: Designing a User Interface with Interface Builder Whats Next?

Whats Next?
Now that your project is complete, you may want to do some further reading. To learn more about the concepts and tasks introduced here, read the chapter on designing user interfaces in Xcode 4 User Guide .

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

50

Document Revision History

This table describes the changes to Xcode Quick Start Guide .

Date 2011-05-07 2011-03-02

Notes Updated the Interface Builder tutorial. New document that provides a hands-on introduction to Xcode.

2011-05-07 | 2011 Apple Inc. All Rights Reserved.

51

Apple Inc. 2011 Apple Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Inc., with the following exceptions: Any person is hereby authorized to store documentation on a single computer for personal use only and to print copies of documentation for personal use provided that the documentation contains Apples copyright notice. The Apple logo is a trademark of Apple Inc. No licenses, express or implied, are granted with respect to any of the technology described in this document. Apple retains all intellectual property rights associated with the technology described in this document. This document is intended to assist application developers to develop applications only for Apple-labeled computers. Apple Inc. 1 Infinite Loop Cupertino, CA 95014 408-996-1010 App Store is a service mark of Apple Inc. Apple, the Apple logo, Cocoa, iPod, Mac, Mac OS, Objective-C, OS X, Quartz, and Xcode are trademarks of Apple Inc., registered in the United States and other countries. IOS is a trademark or registered trademark of Cisco in the U.S. and other countries and is used under license.
Even though Apple has reviewed this document, APPLE MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS DOCUMENT, ITS QUALITY, ACCURACY, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. AS A RESULT, THIS DOCUMENT IS PROVIDED AS IS, AND YOU, THE READER, ARE ASSUMING THE ENTIRE RISK AS TO ITS QUALITY AND ACCURACY. IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES RESULTING FROM ANY DEFECT OR INACCURACY IN THIS DOCUMENT, even if advised of the possibility of such damages. THE WARRANTY AND REMEDIES SET FORTH ABOVE ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL OR WRITTEN, EXPRESS OR IMPLIED. No Apple dealer, agent, or employee is authorized to make any modification, extension, or addition to this warranty. Some states do not allow the exclusion or limitation of implied warranties or liability for incidental or consequential damages, so the above limitation or exclusion may not apply to you. This warranty gives you specific legal rights, and you may also have other rights which vary from state to state.

You might also like