Xcode Quick Tour iPhone OS

42
Xcode Quick Tour for iPhone OS Development Environments: Xcode 2008-10-15

description

iphone Xcode Programe Calculator

Transcript of Xcode Quick Tour iPhone OS

Page 1: Xcode Quick Tour iPhone OS

Xcode Quick Tour for iPhone OSDevelopment Environments: Xcode

2008-10-15

Page 2: Xcode Quick Tour iPhone OS

Apple Inc.© 2008 Apple Inc.All rights reserved.

No part of this publication may be reproduced,stored in a retrieval system, or transmitted, inany form or by any means, mechanical,electronic, photocopying, recording, orotherwise, without prior written permission ofApple Inc., with the following exceptions: Anyperson is hereby authorized to storedocumentation on a single computer forpersonal use only and to print copies ofdocumentation for personal use provided thatthe documentation contains Apple’s copyrightnotice.

The Apple logo is a trademark of Apple Inc.

Use of the “keyboard” Apple logo(Option-Shift-K) for commercial purposeswithout the prior written consent of Apple mayconstitute trademark infringement and unfaircompetition in violation of federal and statelaws.

No licenses, express or implied, are grantedwith respect to any of the technology describedin this document. Apple retains all intellectualproperty rights associated with the technologydescribed in this document. This document isintended to assist application developers todevelop applications only for Apple-labeledcomputers.

Every effort has been made to ensure that theinformation in this document is accurate. Appleis not responsible for typographical errors.

Apple Inc.1 Infinite LoopCupertino, CA 95014408-996-1010

.Mac is a registered service mark of Apple Inc.

Apple, the Apple logo, Cocoa, iTunes, Mac, MacOS, and Xcode are trademarks of Apple Inc.,registered in the United States and othercountries.

iPhone is a trademark of Apple Inc.

Simultaneously published in the United Statesand Canada.

Even though Apple has reviewed this document,APPLEMAKESNOWARRANTYORREPRESENTATION,EITHER EXPRESS OR IMPLIED, WITH RESPECT TOTHIS DOCUMENT, ITS QUALITY, ACCURACY,MERCHANTABILITY,OR FITNESS FORAPARTICULARPURPOSE. AS A RESULT, THIS DOCUMENT ISPROVIDED “AS IS,” AND YOU, THE READER, ARE

ASSUMING THE ENTIRE RISK AS TO ITS QUALITYAND ACCURACY.

IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT,INDIRECT, SPECIAL, INCIDENTAL, ORCONSEQUENTIALDAMAGESRESULTINGFROMANYDEFECTOR INACCURACY IN THIS DOCUMENT, evenif advised of the possibility of such damages.

THEWARRANTYANDREMEDIES SET FORTHABOVEARE EXCLUSIVE AND IN LIEUOF ALL OTHERS, ORALOR WRITTEN, EXPRESS OR IMPLIED. No Appledealer, agent, or employee is authorized to makeany modification, extension, or addition to thiswarranty.

Some states do not allow the exclusion or limitationof implied warranties or liability for incidental orconsequential damages, so the above limitation orexclusionmay not apply to you. Thiswarranty givesyou specific legal rights, and you may also haveother rights which vary from state to state.

Page 3: Xcode Quick Tour iPhone OS

Contents

Introduction Introduction 7

Organization of This Document 7Companion Files 8See Also 8

Chapter 1 Xcode Quick Tour Overview 9

The Development Environment 9Further Reading 11

Chapter 2 Creating the Project 13

Chapter 3 Implementing the Model Object 15

Chapter 4 Implementing Controller Objects 19

Chapter 5 Customizing the Application Delegate 21

Chapter 6 Designing the View 23

Creating the View 23Adding the Display 25Creating the Keypad 27

Chapter 7 Connecting the View Controller to the View 35

Chapter 8 Setting the Application Icon 37

Chapter 9 Running the Application 39

Document Revision History 41

32008-10-15 | © 2008 Apple Inc. All Rights Reserved.

Page 4: Xcode Quick Tour iPhone OS

42008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C O N T E N T S

Page 5: Xcode Quick Tour iPhone OS

Figures and Listings

Chapter 1 Xcode Quick Tour Overview 9

Figure 1-1 The Calc application 11

Chapter 3 Implementing the Model Object 15

Listing 3-1 Calculator.h 15Listing 3-2 Calculator.m 16

Chapter 4 Implementing Controller Objects 19

Listing 4-1 CalcViewController.h 19Listing 4-2 CalcViewController.m 20

Chapter 5 Customizing the Application Delegate 21

Listing 5-1 CalcAppDelegate.h 21Listing 5-2 CalcAppDelegate.m 21

Chapter 6 Designing the View 23

Figure 6-1 CalcView document window 24Figure 6-2 Adding a text field to the view 26Figure 6-3 Resizing a text field 26Figure 6-4 Adding a button to the view 28Figure 6-5 Setting a button’s size 29Figure 6-6 Duplicating a button 30Figure 6-7 Duplicating two buttons 31Figure 6-8 Finished button grid of CalcView 31

Chapter 8 Setting the Application Icon 37

Figure 8-1 Specifying the application icon 38

Chapter 9 Running the Application 39

Figure 9-1 Calc project window after a successful build 39Figure 9-2 Editor window showing error message 40

52008-10-15 | © 2008 Apple Inc. All Rights Reserved.

Page 6: Xcode Quick Tour iPhone OS

62008-10-15 | © 2008 Apple Inc. All Rights Reserved.

F I G U R E S A N D L I S T I N G S

Page 7: Xcode Quick Tour iPhone OS

Xcode provides an ideal environment in which to develop iPhone applications. The iPhone Reference Librarycontains several introductory documents and tutorials to help you learn about this environment. They mostlyteach the paradigms used in the design and implementation of iPhone applications. This document showcasesthe tools used to develop iPhone applications.

This document is tailored to people new to iPhone development who want to learn how Xcode streamlinesthe development process and get a focused introduction to the main Xcode tools used in iPhone applicationdevelopment.

To follow the instructions this document provides, you should be familiar with Cocoa-based applicationdevelopment. See Cocoa Fundamentals Guide for a detailed discussion of the essential concepts you shouldbe familiar with.

Organization of This Document

This document contains the following chapters:

■ “Xcode Quick Tour Overview” (page 9) provides an overview of the main Xcode tools and the projectthis document uses to showcase them.

■ “Creating the Project” (page 13) describes how create a iPhone project from a project template.

■ “Implementing the Model Object” (page 15) touches on the design of model objects and their place inthe Model-View-Controller paradigm.

■ “Implementing Controller Objects” (page 19) describes how to write controller objects in Xcode.

■ “Customizing the Application Delegate” (page 21) shows how to add controller-object management inthe application delegate.

■ “Designing the View” (page 23) guides you through the creation of a simple user interface in InterfaceBuilder.

■ “Connecting the View Controller to the View” (page 35) shows how to connect a view controller to theview it manages in Interface Builder.

■ “Setting the Application Icon” (page 37) illustrates the process of creating an application icon and addingit to an iPhone application project.

■ “Running the Application” (page 39) shows how to build and run an application.

Organization of This Document 72008-10-15 | © 2008 Apple Inc. All Rights Reserved.

I N T R O D U C T I O N

Introduction

Page 8: Xcode Quick Tour iPhone OS

Companion Files

To aid you in following the quick tour, the web version of this document contains a downloadable archivethat contains two source files, Calculator.h and Calculator.m. You may use this archive while followingthe instructions in “Implementing the Model Object” (page 15).

See Also

■ XcodeOverviewdescribes Xcode and its major components, and provides and overview of the developmentprocess.

■ Your First iPhone Application introduces application development for iPhone.

■ iPhone Application Programming Guide describes the technologies and frameworks used to developiPhone applications.

■ iPhone Development Guide describes how to configure computers for iPhone development and explainshow to use Xcode.

■ Interface BuilderUserGuide provides conceptual information and tasks explaining how to use the InterfaceBuilder application to design user interfaces.

8 Companion Files2008-10-15 | © 2008 Apple Inc. All Rights Reserved.

I N T R O D U C T I O N

Introduction

Page 9: Xcode Quick Tour iPhone OS

Xcode is the IDE (integrated development environment) used to develop iPhone applications. Xcode comprisesapplications, command-line tools, libraries, and other resources that make developing iPhone applicationsa gratifying experience.

This chapter provides a short introduction to Xcode. It also provides links to documents that provide detailsabout the concepts it introduces.

The Development Environment

The center of Xcode is the Xcode application. Using this application you create the projects that contain allthe ingredients you need to develop your application. The Xcode application is also your gateway tocommunity resources such as the iPhone Dev Center, documentation, and mailing lists.

During the various stages of the development process, you focus your attention on different Xcode applicationsand tools:

■ Interface Builder. This application lets you design compelling user interfaces graphically. Your work issaved as nib files that your application loads at runtime. This means that what you design is exactly whatusers of your application see; you work with the actual controls that iPhone OS places on the user’sscreen. It also means that you spend less effort writing code for the user-interface–related aspects ofyour application.

■ Text editor. Although Xcode reduces the time you spend writing code, you still spend a considerablepart of your development time in the text editor. To that end, the text editor provides many featureswith the aim of making your source-code editing a productive and efficient endeavor. Code folding,code completion, refactoring, and other features allow you to focus your attention on the right areasand to use your time as efficiently as possible.

■ Debugger. As you start testing your application, you may need to step through your code to determinethe cause of unexpected behavior. The Xcode debugging facilities provide the usual debugging featuressuch as breakpoints, viewing variables, and so forth, but Xcode provides them right in the text editor.That is, you can make a change in your code, add a breakpoint, start your application, and perform mostdebugging tasks in the same window.

The Development Environment 92008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 1

Xcode Quick Tour Overview

Page 10: Xcode Quick Tour iPhone OS

■ Instruments. As you near the end of the development process, you must ensure your application usesthe resources of the device on which it’s running as efficiently as possible, so that battery power is notwasted and your application does not use system resources unnecessarily. The Instruments applicationshows your application’s resource usage, including memory, CPU, and network, in a graphical timelinethat lets you see how your application behaves over time.

The remainder of this document walks you through the development of a very simple application, with thepurpose of showing you some of the Xcode features that make developing iPhone applications an engagingexperience.

This document focuses on the tools rather than the design patterns and conventions of iPhone applicationdevelopment. However, it’s based on the Model-View-Controller design pattern that pervades iPhonedevelopment, in which an application’s design is separated into data, user interface, and the glue code thatlinks those two together. For more information on the design patterns used in iPhone application development,see Cocoa Fundamentals Guide.

This quick tour guides you through the development of the Calc application (shown in Figure 1-1), a verysimple calculator. This document shows you how to:

1. Implement model objects.

2. Implement a controller object.

3. Customize the application delegate to instantiate a view controller and add its view to the applicationwindow.

4. Design a view object using Interface Builder.

5. Connect a view controller to its view in Interface Builder.

6. Temporarily set the application’s icon using its main view.

10 The Development Environment2008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 1

Xcode Quick Tour Overview

Page 11: Xcode Quick Tour iPhone OS

Figure 1-1 The Calc application

Further Reading

These documents provide detailed information about the tools introduced earlier:

■ Interface Builder User Guide describes how to use Interface Builder to design user interfaces.

■ “The Text Editor” explores the capabilities of the Xcode text editor.

■ Xcode Debugging Guide describes how to use the Xcode debugger to find and fix execution problemsin your code.

■ Instruments User Guide shows how to use the Instruments application to gather performance metricsabout your application.

Further Reading 112008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 1

Xcode Quick Tour Overview

Page 12: Xcode Quick Tour iPhone OS

12 Further Reading2008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 1

Xcode Quick Tour Overview

Page 13: Xcode Quick Tour iPhone OS

Xcode provides several iPhone project templates to get you started in your application’s development. Theappropriate template for your needs depends on the type of iPhone application you want to create. Thisdocument uses the Window-Based Application template, which implements a minimal iPhone applicationproject.

This chapter shows you how to create the Calc project.

1. Launch the Xcode application, located in <Xcode>/Applications.

<Xcode> refers to the directory in which you installed the iPhone SDK. Unless you chose a differentdirectory during the installation process, this directory is /Developer.

2. Choose File > New Project.

3. In the New Project dialog, select Application (under iPhone OS) and choose the Window-Based Applicationtemplate.

4. Choose a location for your project.

132008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 2

Creating the Project

Page 14: Xcode Quick Tour iPhone OS

5. Name the project Calc.

The Calc project window opens.

Here’s a description of some of the files in the project:

■ Calc.app: The application binary, the project’s product. It’s in red because the product hasn’t beenbuilt yet. See "How Files Are Referenced" in Xcode Project Management Guide for details.

■ CalcAppDelegate.h, CalcAppDelegate.m: The files that implement the application’s delegate.

■ MainWindow.xib: The nib file that defines the application’s main window. (Nib files contain anapplication’s configured user-interface objects. See Interface Builder User Guide for more informationabout nib files.) Despite its name, iPhone applications normally have only one window. This quick tourshows how to add CalcView.xib, the nib file that defines a view object.

To learn more about the project window, see The Project Window.

142008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 2

Creating the Project

Page 15: Xcode Quick Tour iPhone OS

Model objects are the data an application uses to populate its user interface. In the Calc application themodel object is a class that implements a calculator. This calculator receives keystrokes as input and providesa display value the controller object accesses to obtain calculation results. To learn more about model objects,see The Model-View-Controller Design Pattern.

The source code for the Calculator class is listed in Listing 3-1 and Listing 3-2 (page 16). It’s also includedin this document’s companion files.

Listing 3-1 Calculator.h

/* Calculator.h** Calculator information** Input:* Digits* .0123456789** Operators* +-×/=** Commands:* D Delete* C Clear*/

#import <UIKit/UIKit.h>

@interface Calculator : NSObject {@private

NSMutableString *_display;double _operand;NSString *_operator;

}

- init;- (void) dealloc;

/*** Input into the calculator.** Valid characters: .0123456789+-×/=DC*/- (void) input:(NSString *) character;

/*** The calculator’s “display.”

152008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 3

Implementing the Model Object

Page 16: Xcode Quick Tour iPhone OS

*/- (NSString *) displayValue;

@end

Listing 3-2 Calculator.m

/* Calculator.m*/#import "Calculator.h"

const NSString *Operators = @"+-x/";const NSString *Equals = @"=";const NSString *Digits = @"0123456789.";const NSString *Delete = @"D";const NSString *Clear = @"C";

@implementation Calculator

#pragma mark Internal API- (NSString *) operator {

return _operator;}- (void) setOperator:(NSString *) operator {

if (_operator != operator) {[_operator release];_operator = [operator retain];

}}

#pragma mark Lifecycle- init {

if (self = [super init]) {_display = [[NSMutableString stringWithCapacity:20] retain];_operator = nil;

}return self;

}- (void) dealloc {

[_display release];[_operator release];[super dealloc];

}

#pragma mark Calculator Operation- (void) input:(NSString *) character {

static BOOL last_character_is_operator = NO;if ([Digits rangeOfString: character].length) {

if (last_character_is_operator) {[_display setString: character];last_character_is_operator = NO;

}else if (![character isEqualToString: @"."] || [_display rangeOfString:

@"."].location == NSNotFound) {

162008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 3

Implementing the Model Object

Page 17: Xcode Quick Tour iPhone OS

[_display appendString:character];}

}else if ([Operators rangeOfString:character].length || [character

isEqualToString:(NSString *)Equals]) {if (!_operator && ![character isEqualToString:(NSString *)Equals]) {

_operand = [[self displayValue] doubleValue];[self setOperator: character];

}else {

if (_operator) {double operand2 = [[self displayValue] doubleValue];switch ([Operators rangeOfString: _operator].location) {

case 0:_operand = _operand + operand2;break;

case 1:_operand = _operand - operand2;break;

case 2:_operand = _operand * operand2;break;

case 3:_operand = _operand / operand2;break;

}[_display setString: [[NSNumber numberWithDouble: _operand] stringValue]];

}[self setOperator: ([character isEqualToString:(NSString *)Equals])? nil :

character];}last_character_is_operator = YES;

}else if ([character isEqualToString:(NSString *)Delete]) {

NSInteger index_of_char_to_remove = [_display length] - 1;if (index_of_char_to_remove >= 0) {

[_display deleteCharactersInRange:NSMakeRange(index_of_char_to_remove, 1)];last_character_is_operator = NO;

}}else if ([character isEqualToString:(NSString *)Clear]) {

if ([_display length]) {[_display setString:[NSString string]];

}else {

[self setOperator:nil];}

}}

#pragma mark Outlets- (NSString *) displayValue {

if ([_display length]) {return [[_display copy] autorelease];

}return @"0";

}

172008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 3

Implementing the Model Object

Page 18: Xcode Quick Tour iPhone OS

@end

You can add these source code files to your project in two ways:

■ If you have access to this document’s companion files, add the files to the project:

1. In the Groups & Files list, select Classes.

2. Choose Project > Add to Project.

3. Navigate to the location of this document’s companion files.

4. Select the files and click Add.

5. In the dialog that appears, ensure the copy option is selected.

■ Otherwise, create empty source files and paste the source from the listings:

1. In the Groups & Files list, select Classes.

2. Choose File > New File.

3. In the New File dialog, choose Cocoa Touch Classes > NSObject subclass.

4. Name the class Calculator and ensure the option to create the header file is selected.

5. Enter the source code in this section into the corresponding files in your project.

Later chapters show how to use the Calculator model class in a controller class, CalcViewController.

182008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 3

Implementing the Model Object

Page 19: Xcode Quick Tour iPhone OS

Controller objects, the glue objects in the Model-View-Controller paradigm, manage communication betweenview objects and model objects. They interpret user-interface interactions in a way that model objects canunderstand and present the data the model objects provide in a way that’s easily understood by users. Formore information about controller objects, see The Model-View-Controller Design Pattern.

The CalcViewController object creates an instance of the Calculator class and serves as the intermediarybetween the Calculator object and the action messages sent by the controls in the CalcView object (see“Designing the View” (page 23)).

To create the CalcViewController class, a subclass of UIViewController:

1. In the Groups & Files list, select Classes.

2. Choose File > New File.

3. Choose iPhone OS > Cocoa Touch Classes > UIViewController subclass.

4. Name the class CalcViewController.

5. Edit the CalcViewController.h file.

Add the highlighted lines in Listing 4-1. As you edit the file, note how code completion helps you typeless; to accept its suggestions, press Return. See "Completing Code" in Xcode Workspace Guide for moreinformation.

Listing 4-1 CalcViewController.h

#import <UIKit/UIKit.h>#import "Calculator.h"

@interface CalcViewController : UIViewController {IBOutlet id displayField;Calculator *_calculator;

}- (IBAction) press:(id)sender;@end

6. Save the file.

7. Edit the CalcViewController.m file.

To switch from the header file to the corresponding implementation file (CalcViewController.m) inthe editor, choose View > Switch to Header/Source File.

Add the highlighted lines in Listing 4-2.

192008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 4

Implementing Controller Objects

Page 20: Xcode Quick Tour iPhone OS

Listing 4-2 CalcViewController.m

#import "CalcViewController.h"

@implementation CalcViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{

if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {// Initialization code

_calculator = [Calculator new];}return self;

}

- (void)dealloc {[_calculator release];[super dealloc];

}

- (IBAction) press:(id)sender {[_calculator input:[sender titleForState:UIControlStateNormal]];[displayField setText:[_calculator displayValue]];

}

@end

8. Save the file.

202008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 4

Implementing Controller Objects

Page 21: Xcode Quick Tour iPhone OS

The application delegate is an object to which the UIApplication object delegates some of itsresponsibilities. A delegate allows you to customize or extend the behavior of a class without subclassing it.For background information about how delegates are used in iPhone application development, see Delegatesand Data Sources.

To customize the Calc application delegate:

1. In the Groups & Files list, select Classes.

2. Edit CalcAppDelegate.h by adding the highlighted lines in Listing 5-1.

Listing 5-1 CalcAppDelegate.h

#import <UIKit/UIKit.h>

@class CalcViewController;

@interface CalcAppDelegate : NSObject <UIApplicationDelegate> {IBOutlet UIWindow *window;CalcViewController *calcViewController;

}

@property (nonatomic, retain) UIWindow *window;@property (nonatomic, retain) CalcViewController *calcViewController;

@end

Save the file.

3. Edit CalcAppDelegate.m by adding the highlighted lines in Listing 5-2.

Use the Edit > Select Next Placeholder command (or press Command-/) to move between the argumentsof the initWithNibName:bundle: method when the editor offers that completion.

Listing 5-2 CalcAppDelegate.m

#import "CalcAppDelegate.h"#import "CalcViewController.h"

@implementation CalcAppDelegate

@synthesize window;@synthesize calcViewController;

- (void)applicationDidFinishLaunching:(UIApplication *)application {CalcViewController *_calcViewController = [[CalcViewController alloc]

initWithNibName:@"CalcView" bundle:nil];self.calcViewController = _calcViewController;

212008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 5

Customizing the Application Delegate

Page 22: Xcode Quick Tour iPhone OS

[window addSubview:[calcViewController view]];[window makeKeyAndVisible];

}

- (void)dealloc {[calcViewController release];[window release];[super dealloc];

}

@end

4. Save the file.

222008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 5

Customizing the Application Delegate

Page 23: Xcode Quick Tour iPhone OS

To get users excited about your application, it should have the best user interface possible. The InterfaceBuilder application allows you to build beautiful, and more importantly, useful user interfaces by draggingcontrols from a library of user-interface elements and laying them out in a view as you want them to appearto the user. Your user-interface designs are known as nib files. Your application loads these resources atruntime to reconstitute the user interface you designed. This means that you can make substantial changesto the user interface layout (and even some of its behavior) without having to edit source code. This is themain benefit of the Model-View-Controller paradigm. See Application Interface Basics for more information.

In this chapter you add the CalcView view object to the Calc application’s main user interface.

Creating the View

Begin by creating the nib file and associating it with the CalcViewController class.

1. In the Groups & Files list, select Resources.

2. Choose File > New File.

3. Under the iPhone OS platform, select the User Interfaces template group, and choose the View XIBtemplate.

4. Name the file CalcView.xib.

5. Double-click CalcView.xib to open it in Interface Builder.

Creating the View 232008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 6

Designing the View

Page 24: Xcode Quick Tour iPhone OS

Figure 6-1 shows the CalcView.xib document window, which contains three proxy objects.

Figure 6-1 CalcView document window

6. Set the File’s Owner type to CalcViewController.

This is how Interface Builder is able to get information about the class from Xcode.

a. In the CalcView.xib window, select the File’s Owner proxy object.

b. Choose Tools > Inspector.

c. Display the Identity pane.

d. Enter CalcViewController in the Class text field. Note that Interface Builder autocompletes“CalcViewController” because it knows about it through its connection with Xcode. Interface Builderalso adds the press: action method and displayField outlets declared inCalcViewController.h. Every time you save header files in Xcode, Interface Builder reads themand updates its proxy objects with the outlets (instance variables) and action methods they declare.

7. Set the View object’s attributes.

a. Select the View object.

b. Display the Attributes pane in the inspector.

24 Creating the View2008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 6

Designing the View

Page 25: Xcode Quick Tour iPhone OS

c. Set the View object’s background to black.

Adding the Display

In this section, you create the text field in which the numbers the user enters and the calculation resultsappear.

1. Add a text field to the View object.

a. Choose Tools > Library to open the Interface Builder library.

b. In the Organization pane, select Library > Cocoa Touch Plugin > Inputs & Values.

c. Drag the Text Field item onto the view.

Adding the Display 252008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 6

Designing the View

Page 26: Xcode Quick Tour iPhone OS

Position the text field as shown in Figure 6-2.

Figure 6-2 Adding a text field to the view

2. Enlarge the text field so that it spans most of the view’s width, as shown in Figure 6-3.

Figure 6-3 Resizing a text field

3. Make the following settings in the Attributes pane in the inspector:

a. Set the text field text to 0 and press Tab.

b. Set the alignment to right-align.

4. Set the title typeface and size:

26 Adding the Display2008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 6

Designing the View

Page 27: Xcode Quick Tour iPhone OS

a. Select the text field in the view.

b. Choose Font > Show Fonts.

c. In the Fonts window, select Bold, then select 36.

Creating the Keypad

Now you’re ready to add the buttons that implement the calculator’s keypad.

Creating the Keypad 272008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 6

Designing the View

Page 28: Xcode Quick Tour iPhone OS

1. Drag a round rect button from the Library to the view, as shown in Figure 6-4.

Figure 6-4 Adding a button to the view

28 Creating the Keypad2008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 6

Designing the View

Page 29: Xcode Quick Tour iPhone OS

2. In the Size pane in the inspector, set the button’s width to 64 and its height to 70, as shown in Figure6-5.

Figure 6-5 Setting a button’s size

3. Make the following settings in the Attributes pane in the inspector:

a. Set the title color to black.

b. Set the button title to 7 (press Tab to commit the change).

Creating the Keypad 292008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 6

Designing the View

Page 30: Xcode Quick Tour iPhone OS

c. Set the font size to 48.

4. To copy the button with its attributes, choose Edit > Duplicate.

Position the copy as shown in Figure 6-6.

Figure 6-6 Duplicating a button

Note: You can also Option-drag controls to duplicate them.

5. Select the two buttons and duplicate them.

30 Creating the Keypad2008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 6

Designing the View

Page 31: Xcode Quick Tour iPhone OS

Position the copies as shown in Figure 6-7.

Figure 6-7 Duplicating two buttons

6. Perform similar steps to create the grid shown in Figure 6-8.

Note that the last row is made up to two double-witdh buttons.

Also, replace the buttons’ titles to match the arrangement in the figure.

Figure 6-8 Finished button grid of CalcView

7. Connect each button to the File’s Owner press: action method.

a. Select the 7 button.

Creating the Keypad 312008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 6

Designing the View

Page 32: Xcode Quick Tour iPhone OS

b. Control-drag from the button to the File’s Owner (the CalcViewController object) in theCalcView.xib window

c. Release the mouse button and choose the press: event from the menu that appears.

32 Creating the Keypad2008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 6

Designing the View

Page 33: Xcode Quick Tour iPhone OS

The Button Connections pane in the inspector shows that the button’s Touch Up Inside event sendsthe press: message to the File’s Owner.

Repeat these steps for all the buttons in the grid.

8. Save the CalcView.xib file.

Creating the Keypad 332008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 6

Designing the View

Page 34: Xcode Quick Tour iPhone OS

34 Creating the Keypad2008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 6

Designing the View

Page 35: Xcode Quick Tour iPhone OS

“Designing the View” (page 23) shows how to connect view objects to a controller object. This chapter showshow to connect controller objects to view objects in Interface Builder.

To connect CalcViewController to its view and the view’s text field (to display the Calculator instance’s“screen”):

1. In the CalcView.xib window, select the File’s Owner proxy (which represents an instance of theCalcViewController class).

2. In the Connections pane in the inspector, connect the displayField outlet to the text field in the view.

3. Connect the view outlet to the view.

4. Save the CalcView.xib file.

352008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 7

Connecting the View Controller to the View

Page 36: Xcode Quick Tour iPhone OS

362008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 7

Connecting the View Controller to the View

Page 37: Xcode Quick Tour iPhone OS

Your application’s icon identifies it among the set of applications a user may have installed on their device.To that end, your icon should be unique. An application icon file must be a PNG file named icon.png. Youshould use a professionally designed icon.

In this chapter, you generate the application icon by taking a snapshot of your main view. However, this isnot the method that you should follow for applications you release to your customers. For details aboutgenerating the application icons users see in iPhone OS, the App Store, and iTunes, see “Application Iconand Launch Images” in iPhone Application Programming Guide.

To specify your application’s icon in the project, you add an icon.png file to the project and identify thatfile in your application’s Info.plist file:

1. In Interface Builder, take a snapshot of the Calc button grid.

Press Shift-Comand-4 and drag from the top-left corner to the bottom-right corner of the grid.

Mac OS X places the snapshot file in your Desktop using the name Picture 1.png (or a name with ahigher number if you’ve captured other snapshots).

2. Rename the snapshot file icon.png.

372008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 8

Setting the Application Icon

Page 38: Xcode Quick Tour iPhone OS

3. In the Groups & Files list, select Resources.

4. Choose Project > Add to Project.

5. Navigate to your Desktop directory and choose icon.png.

6. In the dialog that appears, ensure the copy option is selected, and click Add.

7. In the Groups & Files list, double-click Info.plist under Resources.

8. In the editor window, set the value of the Icon file key to icon.png, as shown in Figure 8-1.

Figure 8-1 Specifying the application icon

9. Save the Info.plist file.

382008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 8

Setting the Application Icon

Page 39: Xcode Quick Tour iPhone OS

To run the Calc application, you must build it first. In Xcode, choose Build > Build.

If there are no build problems, the project window should look similar to Figure 9-1.

Figure 9-1 Calc project window after a successful build

If there are build errors, they are listed in the Errors and Warnings group in the Groups & Files list. The texteditor also shows message bubbles with information about build errors and warnings, as Figure 9-2 shows.

392008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 9

Running the Application

Page 40: Xcode Quick Tour iPhone OS

Figure 9-2 Editor window showing error message

To run Calc, choose Run > Run.

If you don’t have a development device connected to your computer, the application runs in iPhone Simulator.Otherwise, Xcode installs your application on your device and launches it.

iPhone Simulator allows you to run and test iPhone applications even when you don’t have a developmentdevice available. However, the simulator and device environments are different. iPhone Simulator is a Macapplication running on an architecture different from the one present in devices. To learn about the differencesbetween the two environments, see iPhone Development Guide.

402008-10-15 | © 2008 Apple Inc. All Rights Reserved.

C H A P T E R 9

Running the Application

Page 41: Xcode Quick Tour iPhone OS

This table describes the changes to Xcode Quick Tour for iPhone OS.

NotesDate

Made content corrections.2008-10-15

New document that showcases the tools used to develop iPhone applications.2008-05-28

412008-10-15 | © 2008 Apple Inc. All Rights Reserved.

R E V I S I O N H I S T O R Y

Document Revision History

Page 42: Xcode Quick Tour iPhone OS

422008-10-15 | © 2008 Apple Inc. All Rights Reserved.

R E V I S I O N H I S T O R Y

Document Revision History