Sei sulla pagina 1di 60

Your First iOS App

General

2011-10-12

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, Cocoa Touch, Instruments, iPhone, iTunes, Mac, Mac OS, Objective-C, and Xcode are trademarks of Apple Inc., registered in the United States and other countries. iPad is a trademark of Apple Inc. 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.

Contents
Introduction

About Creating Your First iOS App 5


At a Glance 6 Becoming Familiar with the Tools and the Design Patterns 6 Learning About the Roles of View Controllers and Views 6 Writing Code to Perform a Custom Task 6 Solving Problems and Choosing Your Next Steps 7 See Also 7

Chapter 1

Getting Started 9
Create and Test a New Project 9 Find Out How an Application Starts Up 15 Recap 20

Chapter 2

Understanding Fundamental Design Patterns 21


Cocoa Touch Provides the Frameworks You Need for iOS App Development 21 Delegation Helps You Add Functionality Without Subclassing 21 Model-View-Controller Makes Code Easier to Write and Reuse 22 The Target-Action Pattern Enables Responses to User Interactions 22 Other Design Patterns 23

Chapter 3

Inspecting the View Controller and Its View 25


Use the Inspector to Examine the View Controller 25 Change the Views Background Color 28 Recap 31

Chapter 4

Configuring the View 33


Add the User Interface Elements 33 Create an Action for the Button 37 Create Outlets for the Text Field and the Label 40 Make the Text Fields Delegate Connection 44 Test the Application 46 Recap 46

Chapter 5

Implementing the View Controller 47


Add a Property for the Users Name 47 Implement the changeGreeting: Method 49

3
2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CONTENTS

Configure the View Controller as the Text Fields Delegate 50 Test the Application 51 Recap 51 Chapter 6

Troubleshooting 53
Code and Compiler Warnings 53 Check the Storyboard File 53 Delegate Method Names 53

Chapter 7

Next Steps 55
Improve the User Interface 55 Install the Application on a Device 55 Add More Functionality 55 Add Unit Tests 56

Appendix A

Code Listings 57
The Interface file: HelloWorldViewController.h 57 The Implementation File: HelloWorldViewController.m 57

Document Revision History 59

4
2011-10-12 | 2011 Apple Inc. All Rights Reserved.

INTRODUCTION

About Creating Your First iOS App

Your First iOS Application introduces you to the Three Ts of iOS app development:

Tools. How to use Xcode to create and manage a project. Technologies. How to create an application that responds to user input. Techniques. How to take advantage of the fundamental design patterns that underlie all iOS app development.

After you complete all the steps in this tutorial, youll have an app that accepts your input and prints it on the screen:

5
2011-10-12 | 2011 Apple Inc. All Rights Reserved.

INTRODUCTION

About Creating Your First iOS App

To benefit from this tutorial, you must already have some familiarity with the basics of computer programming in general and with the Objective-C language in particular. If you havent used Objective-C before, read Learning Objective-C: A Primer before you begin this tutorial. Note: You can use this tutorial to get started with iOS app development even if you intend to develop solely for iPad. Although this tutorial shows the iPhone user interface, the tools and techniques you use are exactly the same as those you use to develop iPad applications.

At a Glance
Following this tutorial helps you get started on the path to developing great iOS apps. Although the app you create in this tutorial is very simple, it will help you get comfortable with the iOS development environment and introduce you to the powerful design patterns that characterize the best iOS apps.

Becoming Familiar with the Tools and the Design Patterns


iOS apps are developed in Xcode, Apples integrated development environment. Xcode includes several developer tools and is tightly integrated with the programming frameworks you use to code your app. As you begin coding your app, you need to learn how successful iOS apps are structured and how some key design patterns can help you write better code. Relevant chapters: Getting Started (page 9), Understanding Fundamental Design Patterns (page 21)

Learning About the Roles of View Controllers and Views


In an iOS app, a view is simply an onscreen area that users can see or interact with. A view object can be any size, and it can contain other view objects, such as buttons or images. A view controller is an object that controls one or more views. In this tutorial, you learn about the roles of different objects in your app, and how to create connections between the view controller and the objects that you add to its view. Relevant chapters: Understanding Fundamental Design Patterns (page 21), Inspecting the View Controller and Its View (page 25), Configuring the View (page 33)

Writing Code to Perform a Custom Task


Xcode and the programming frameworks work together to provide a lot of functionality for you, but there will always be custom tasks that an app must perform. In this tutorial, you learn how to implement a custom task by writing a method that gets called when a button is tapped.

At a Glance
2011-10-12 | 2011 Apple Inc. All Rights Reserved.

INTRODUCTION

About Creating Your First iOS App

Relevant chapter: Implementing the View Controller (page 47)

Solving Problems and Choosing Your Next Steps


As you complete the tasks in this tutorial, you might encounter problems that you dont know how to solve. Your First iOS Application outlines a few common errors that you can look for and it includes code listings you can use to compare with the code in your project. After you finish this tutorial, you should think about ways in which you can improve your app and increase your knowledge. There are many directions in which you can go, and Xcode and the iOS programming frameworks can help you implement just about anything you can design. Relevant chapters: Troubleshooting (page 53), Code Listings (page 57), Next Steps (page 55)

See Also
Developing an iOS app is a multistep process that ranges from determining what the app should do to submitting it to the App Store. Your First iOS Application cant help you decide what your apps should do, and it doesnt describe how to submit them to the App Store, but there are many resources that can help you accomplish these and other tasks. Some of these resources are listed here:

To learn about the recommended approaches to designing the user interface and user experience of an iOS app, see iOS Human Interface Guidelines. For comprehensive guidance on creating a full-featured iOS app, see iOS App Programming Guide. To learn about all the tasks you need to perform as you prepare to submit your app to the App Store, see App Development Overview.

See Also
2011-10-12 | 2011 Apple Inc. All Rights Reserved.

INTRODUCTION

About Creating Your First iOS App

See Also
2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 1

Getting Started

To create the iOS application in this tutorial, you need Xcode 4.2. Xcode is Apples integrated development environment (or IDE) for both iOS and Mac OS X development. When you install Xcode on your Mac, you also get the iOS SDK, which includes the programming interfaces of the iOS platform. If you dont have Xcode installed on your Mac, visit the iOS Dev Center and download the Xcode 4.2 developer toolset (which includes the iOS 5 SDK). Double-click the package and follow the installer instructions.

Create and Test a New Project


To get started developing your application, you create a new Xcode project.

To create a new project . . .


1. Open Xcode (by default its in /Developer/Applications). If youve never created or opened a project in Xcode before, you should see a Welcome to Xcode window similar to this:

Create and Test a New Project


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 1

Getting Started

If youve created or opened a project in Xcode before, you might see a project window instead of the Welcome to Xcode window. 2. In the Welcome to Xcode window, click Create a new Xcode project (or choose File > New > New project). Xcode opens a new window and displays a dialog in which you can choose a template. Xcode includes several built-in application templates that you can use to develop common styles of iOS apps. For example, the Tabbed template creates an app that is similar to iTunes and the Master-Detail template creates an app that is similar to Mail.

10

Create and Test a New Project


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 1

Getting Started

3. 4.

In the iOS section at the left side of the dialog, select Application. In the main area of the dialog, select Single View Application and then click Next. A new dialog appears that prompts you to name your application and choose additional options for your project.

Create and Test a New Project


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

11

CHAPTER 1

Getting Started

5.

Fill in the Product Name, Company Identifier, and Class Prefix fields. You can use the following values:

Product Name: HelloWorld Company Identifier: Your company identifier, if you have one. If you dont have a company identifier, you can use edu.self. Class Prefix: HelloWorld

Note: Xcode uses the product name you entered to name your project and the application. Xcode uses the class prefix name you entered to name the classes it creates for you. For example, Xcode automatically creates an application delegate class and names it HelloWorldAppDelegate. If you enter a different value for the class prefix, then the application delegate class is named YourClassPrefixNameAppDelegate. To keep things simple, this tutorial assumes that you named your product HelloWorld and that you used HelloWorld for the class prefix value. 6. 7. In the Device Family pop-up menu, make sure that iPhone is selected. Make sure that the Use Storyboard and Use Automatic Reference Counting options are selected and that the Include Unit Tests option is unselected (these are the default values).

12

Create and Test a New Project


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 1

Getting Started

8.

Click Next. Another dialog appears that allows you to specify where to save your project.

9.

Specify a location for your project (leave the Source Control option unselected) and then click Create. You should see a new project window similar to this:

Even though you havent yet written any code, you can build your application and run it in the Simulator application that is included in Xcode. As its name implies, Simulator allows you to get an idea of how your app would look and behave if it were running on an iOS-based device.

Create and Test a New Project


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

13

CHAPTER 1

Getting Started

To run your application in Simulator . . .


1. Make sure that the Scheme pop-up menu in the Xcode toolbar has HelloWorld > iPhone 5.0 Simulator chosen. If the pop-up menu does not display that choice, open it and choose iPhone 5.0 Simulator from the menu. 2. Click the Run button in the toolbar (or choose Product > Run). Xcode displays various messages that update you on the build process.

After Xcode finishes building your project, Simulator should start automatically. Because you specified an iPhone product (as opposed to an iPad product), Simulator displays a window that looks like an iPhone. On the simulated iPhone screen, Simulator opens your application, which should look like this:

14

Create and Test a New Project


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 1

Getting Started

Right now, your application is not very interesting: it simply displays a blank white screen. To understand where the white screen comes from, you need to learn about the objects in your code and how they work together to start the app. For now, quit Simulator (make sure you dont quit Xcode).

Find Out How an Application Starts Up


Because you based your project on an Xcode template, much of the basic application environment is automatically set up when you run the app. For example, Xcode creates an application object, which connects to the window server, establishes the run loop, and so on. Most of this work is done by the UIApplicationMain function, which is called in the main.m source file.

To look at the main.m source file . . .


1. 2. Open the Supporting Files folder in the project navigator by clicking the disclosure triangle next to it. Select main.m. Xcode opens the source file in the main editor area of the window, which should look similar to this:

Find Out How an Application Starts Up


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

15

CHAPTER 1

Getting Started

The main function in main.m calls the UIApplicationMain function within an autorelease pool:
@autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([HelloWorldAppDelegate class])); }

The @autoreleasepool statement supports the Automatic Reference Counting (ARC) system. ARC provides automatic object-lifetime management for your application, ensuring that objects remain in existence for as long as they're needed and no longer. The call to UIApplicationMain creates an instance of UIApplication and an instance of the application delegate (in this case, HelloWorldAppDelegate). The main function of the app delegate is to provide the window into which your apps content is drawn. The call to UIApplicationMain also scans the applications Info.plist file. The Info.plist file is a property list that contains information about the application such as its name and icon. Find Out How an Application Starts Up
2011-10-12 | 2011 Apple Inc. All Rights Reserved.

16

CHAPTER 1

Getting Started

To look at the property list file . . .

In the Supporting Files folder in the project navigator, select HelloWorld-Info.plist. Xcode opens the Info.plist file in the main editor area of the window, which should look similar to this:

Because you chose to use a storyboard in this project, the Info.plist file also contains the name of the storyboard file that the application object should load. A storyboard file contains an archive of the objects, transitions, and connections that define an applications user interface. To minimize distractions, close the Supporting Files folder in the project navigator by again clicking the disclosure triangle next to it. In this application, the storyboard file is named MainStoryboard.storyboard (note that the Info.plist file shows only the first part of this name). When the app starts, the MainStoryboard.storyboard file is loaded and the initial view controller is instantiated from it.

Find Out How an Application Starts Up


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

17

CHAPTER 1

Getting Started

To look at the storyboard file . . .

Select MainStoryboard.storyboard in the project navigator. Xcode opens the storyboard file in the editor area. (The area behind the storyboard objectsthat is, the area that looks like graph paperis called the canvas.)

When you open the default storyboard file, your project window should look similar to this:

A storyboard file contains scenes and segues. A scene represents a view controller, which manages one area of content, and a segue represents a transition between two scenes.

18

Find Out How an Application Starts Up


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 1

Getting Started

Because the Single View template provides only one area of content which occupies the entire screen, the MainStoryboard file in your app contains only one scene and no segues. (The arrow that points to the left side of the scene on the canvas is the initial scene indicator, which identifies the initial scene in an app.) The scene that you see on the canvas is named Hello World View Controller Scene because it is managed by the HelloWorldViewController object in your application. The Hello World View Controller scene consists of a few items that are displayed in the Xcode outline view (which is the pane that appears between the canvas and the project navigator):

A first responder placeholder object (represented by an orange cube). The first responder is a dynamic placeholder that represents the responder object that first receives events such as keyboard events, motion events, and action messages (youll learn more about action messages in The Target-Action Pattern Enables Responses to User Interactions (page 22)). You wont be doing anything with the first responder in this tutorial, but you can learn more about it in Event Handling Guide for iOS.

The HelloWorldViewController object (represented by a pale rectangle inside a yellow sphere). When a scene in a storyboard file is loaded, it creates an instance of the view controller class that manages it.

A view (which is listed below the view controlleryou might have to open the disclosure triangle next to HelloWorldViewController to reveal it). The white background of this view is what you saw when you ran the application in Simulator.

Note: The area below the scene on the canvas is called the scene dock. Right now, it displays the view controllers name (that is, Hello World View Controller). At other times, the scene dock can contain the icons that represent the first responder and the view controller object. During setup, the application object performs the following tasks:

Loads the main storyboard file. Gets the window object from the app delegate (or creates a new instance of UIWindow and associates it with the app delegate). Instantiates the storyboards initial view controller and assigns it as the window objects root view controller.

When the application object has completed these tasks, it sends its delegate an application:didFinishLaunchingWithOptions: message. This message gives the delegate an opportunity to perform other tasks, such as additional configuration, before the application is displayed. In this tutorial, the application delegate is provided by the Single View template and its called HelloWorldAppDelegate. You will not be changing the default app delegate class in this project, but you will be using delegation in a later step. You can learn more about delegation in Delegation Helps You Add Functionality Without Subclassing (page 21).

Find Out How an Application Starts Up


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

19

CHAPTER 1

Getting Started

Recap
In this chapter you used Xcode to create a new project based on the Single View template. Then, you built and ran the default application that the template defines. You also looked at some of the basic pieces of the project, such as the main.m source file, the Info.plist file, and the storyboard file, and learned how an application starts up. In the next chapter, youll learn about the design patterns that pervade iOS application development and how they apply to your app.

20

Recap
2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 2

Understanding Fundamental Design Patterns

Before you start customizing your app, take a moment to learn about the programming environment youre working in and the design patterns that characterize great iOS applications. You can complete the tutorial without reading this chapter, but if you allow some time to read and think about the concepts it describes, youll have a much better understanding of iOS app development.

Cocoa Touch Provides the Frameworks You Need for iOS App Development
Cocoa Touch is the application environment for all iOS apps (Cocoa provides the application environment for Mac OS X apps). As you develop apps for iOS, including the app in this tutorial, youll rely on the object-oriented frameworks that Cocoa Touch provides. In particular, youll use the application programming interfaces (APIs) of the UIKit framework, which provides all the classes that an app needs to construct and manage its user interface. There are several resources that can help you gain a deeper understanding of Cocoa Touch (and Cocoa). A good place to start is Cocoa Fundamentals Guide.

Delegation Helps You Add Functionality Without Subclassing


Delegation is a design pattern in which one object sends messages to another object that has been specified as its delegate, to ask for input or to notify the delegate that an event is occurring. The delegate object responds to these messages in a custom way. Delegation is a common design pattern in Cocoa Touch apps because it allows you to provide custom behavior without having to subclass and override the methods of a complex framework object, such as UIApplication. Delegate methods are typically grouped together into a protocol. A protocol is basically just a list of methods. If a class conforms to (or adopts) a protocol, it guarantees that it implements the required methods of a protocol. (Protocols can also include optional methods.) A delegate protocol specifies all the messages an object might send to its delegate. For example, the UIApplicationDelegate protocol specifies all the messages that the UIApplication object might send to its delegate, such as application:didFinishLaunchingWithOptions. To learn more about protocols and the role they play in Objective-C, see Protocols. The application in this tutorial uses delegation in two ways:

Every iOS app must have an application delegate object; in this app, its an instance of the HelloWorldAppDelegate class thats provided by the Single View template.

Cocoa Touch Provides the Frameworks You Need for iOS App Development
2011-10-12 | 2011 Apple Inc. All Rights Reserved.

21

CHAPTER 2

Understanding Fundamental Design Patterns

In addition to performing custom configuration tasks, the app delegate can handle application-level events because it participates in the responder chain. In this tutorial, you do not have to perform custom configuration tasks or explicitly handle app-level events, so you do not need to make any changes to the HelloWorldAppDelegate source files.

The text field that youll be adding later needs to tell its delegate when the user is finished typing. To help accomplish this, you ensure that the view controller object (that is, HelloWorldViewController) conforms to the UITextFieldDelegate protocol.

Model-View-Controller Makes Code Easier to Write and Reuse


The Model-View-Controller (MVC) design pattern defines three roles for objects in an application. Model objects represent data, such as space ship objects in a game, to-do items in a calendar app, or shapes in a drawing app. In this application, the model object is very simpleits just a string that holds the name the user enters. Because this string is used in only one method, its not strictly necessary to identify it as a model object, but treating it as such helps you become comfortable with the MVC design pattern. View objects know how to display data (represented by model objects) and can allow the user to edit the data. In this application, you need a main view to contain three other views: A text field to get input from the user, a label to display the text the user entered, and a button the user taps to see their input in the label. Controller objects mediate between models and views. In this application, the view controller object takes the data from the input text field (a view), stores it in a string (the model), and updates the label (another view). The update is initiated as a result of an action message sent by the button.

The Target-Action Pattern Enables Responses to User Interactions


The target-action mechanism allows a control object, such as a button, to send to another object a meaningful message in response to a user-initiated event, such as a tap. For example, consider an app that stores the users contacts: When the user taps an Add Contact button, the button sends an add contact message (the action) to a custom application object (the target) that knows how to add the contact to the contact list. In this application, when the button is tapped, it sends an action message to the controller (the target) that tells it to update its model and view based on the users input.

22

Model-View-Controller Makes Code Easier to Write and Reuse


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 2

Understanding Fundamental Design Patterns

Other Design Patterns


Cocoa Touch makes pervasive use of a number of other design patterns in addition to delegation, MVC, and target-action. Later, when youve finished this tutorial, you should learn about these patterns so that you can employ them as you develop more complicated apps. You can get a great overview of Cocoa design patterns in Cocoa Design Patterns. Understanding Cocoa design patterns makes it easier for you to use the various technologies Cocoa Touch provides, and to transfer the skills you learn in one area to another. Following the patterns also means that your code is better able to take advantage of enhancements to the application frameworks in future releases.

Other Design Patterns


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

23

CHAPTER 2

Understanding Fundamental Design Patterns

24

Other Design Patterns


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 3

Inspecting the View Controller and Its View

As you learned earlier, a view controller is responsible for managing one scene, which represents one area of content. The content that you see in this area is defined in the view controllers view. In this chapter, you take a closer look at your view controller and learn how to adjust the background color of the view.

Use the Inspector to Examine the View Controller


When an app starts up, the main storyboard file is loaded and the initial view controller is instantiated. The initial view controller manages the first scene that users see when they open the app. Because the Single View template provides only one view controller, its automatically set to be the initial view controller. You can verify the status of the view controller, and find out other things about it, by using the Xcode inspector.

To open the inspector . . .


1. If necessary, click MainStoryboard.storyboard in the project navigator to display the scene on the canvas. In the outline view, select Hello World View Controller (its listed below First Responder). Your project window should look something like this:

2.

Use the Inspector to Examine the View Controller


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

25

CHAPTER 3

Inspecting the View Controller and Its View

Note that the scene and the scene dock are both outlined in blue, and the view controller object is selected in the scene dock. 3. 4. Click the rightmost View control in the toolbar to display the utilities area at the right side of the window. Click the Attributes inspector button at the top of the utilities area (its the fourth button from the left and it looks like this: ).

Your project window should look something like this (you might have to resize the Xcode window to see everything):

26

Use the Inspector to Examine the View Controller


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 3

Inspecting the View Controller and Its View

In the Attributes inspector, you can see that the option Initial Scene Is Initial View is selected. Note that if you deselect this option, the initial scene indicator disappears from the canvas. For this tutorial, make sure the Initial Scene option remains selected.

Use the Inspector to Examine the View Controller


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

27

CHAPTER 3

Inspecting the View Controller and Its View

Change the Views Background Color


In Find Out How an Application Starts (page 15), you learned that a view provides the white background that you saw when you ran the app in Simulator. To make sure that your application is working correctly, you can set the background color of the view to something other than white and verify that the new color is displayed by again running the app in Simulator. Before you change the background of the view, make sure that the main storyboard file is still open on the canvas.

To set the background color of the view controllers view . . .


1. In the outline view, click the disclosure triangle next to Hello World View Controller (if its not already open) and select View. Xcode highlights the view area on the canvas. 2. 3. Click the Attributes button at the top of the utilities area to open the Attributes inspector, if its not already open. In the Attributes inspector, click the white rectangle in the Background pop-up menu to open the Colors window. Note: If instead of clicking the white rectangle, you click Default and open the pop-up menu, choose Other from the menu that appears. 4. In the Colors window, select a color other than white. Your project window should look something like this:

28

Change the Views Background Color


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 3

Inspecting the View Controller and Its View

Note that because Xcode highlighted the view when you selected it, the color on the canvas might look different from the color in the Colors window. 5. Close the Colors window.

Test your application in Simulator. You should see something like this:

Change the Views Background Color


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

29

CHAPTER 3

Inspecting the View Controller and Its View

Tip You dont have to save your work before you run your app because when you click Run (or choose Project > Run), Xcode automatically saves the files to which youve made changes.

Before you continue with the tutorial, restore the views background color to white.

To restore the views background color . . .


1. In the Attributes inspector, open the Background pop-up menu by clicking the arrows. Note that if you click the colored rectangle in the Background pop-up menu (instead of the arrows), the Colors window reopens. 2. 3. In the Background pop-up menu, choose the white square listed in the Recently Used Colors section of the menu. Click the Run button to compile and run your app (and save your changes).

30

Change the Views Background Color


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 3

Inspecting the View Controller and Its View

After youve verified that your app again displays a white background, quit Simulator. When you run your app, Xcode might open the Debug area at the bottom of the project window. You wont use this pane in this tutorial, so you can close it to make more room in your window.

To close the Debug area . . .

Click the Debug View button in the toolbar.

The Debug View button is the middle View button and it looks like this:

Recap
In this chapter, you inspected the scene and changed (and restored) the background color of the view. In the next chapter, you add controls to the view.

Recap
2011-10-12 | 2011 Apple Inc. All Rights Reserved.

31

CHAPTER 3

Inspecting the View Controller and Its View

32

Recap
2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 4

Configuring the View

Xcode provides a library of objects that you can add to a storyboard file. Some of these are user interface elements that belong in a view, such as buttons and text fields; others are higher level objects, such as view controllers and gesture recognizers. Your Hello World View Controller scene already contains a viewnow you need to add a button, a label, and a text field. Then, you make connections between these elements and the view controller class so that the elements provide the behavior you want.

Add the User Interface Elements


You add user interface (UI) elements by dragging them from the object library to a view on the canvas. After the UI elements are in a view, you can move and resize them as appropriate.

To add the UI elements to the view and lay them out appropriately . . .
1. If necessary, select MainStoryboard.storyboard in the project navigator to display the scene on the canvas. If necessary, open the object library. The object library appears at the bottom of the utilities area. If you dont see it, you can click the object library button, which looks like this: 3. .

2.

In the object library, choose Controls from the Objects pop-up menu. Xcode displays a list of controls below the pop-up menu. The list displays each controls name and appearance, and a short description of its function.

4.

One at a time, drag a text field, a round rect button, and a label from the list to the view.

Add the User Interface Elements


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

33

CHAPTER 4

Configuring the View

5.

In the view, lay out the UI elements appropriately. As you move UI elements within the view, dashed blue lines appear that help you align the items with the edges of the view and with each other. (These dashed blue lines are called alignment guides.) You can also resize the UI elements by dragging their resize handles. To reveal an elements resize handles, select it (that is, click it once). You can lay out your apps user interface any way you choose, but this tutorial uses the following layout:

34

Add the User Interface Elements


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 4

Configuring the View

6.

In the view, select the text field and then in the Placeholder field of the Text Field Attributes inspector enter the phrase Your Name. In the Text Field Attributes inspector, click the middle Alignment button to center the text fields text. In the Label Attributes inspector, click the middle Alignment button to center the labels text. In the view, double-click the button and enter the text Hello.

7. 8. 9.

After you add the text field, label, and button and make the other recommended changes, your project should look similar to this:

Add the User Interface Elements


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

35

CHAPTER 4

Configuring the View

There are a few other changes you can make to the text field so that it behaves as users expect. First, because users will be entering their names, you can ensure that iOS suggests capitalization for each word they type. Second, you can make sure that the keyboard associated with the text field is configured for entering names (rather than numbers, for example), and that the keyboard displays a Done button. This is the principle behind these changes: Because you know at design time what type of information a text field will contain, you can configure it so that its runtime appearance and behavior are well suited to the users task. You make all of these configuration changes in the Attributes inspector.

To configure the text field . . .


1. In the view, select the text field.

36

Add the User Interface Elements


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 4

Configuring the View

2.

In the Text Field Attributes inspector, make the following choices:


In the Capitalization pop-up menu, choose Words. Ensure that the Keyboard pop-up menu is set to Default. In the Return Key pop-up menu, choose Done.

Run your app in Simulator to make sure that the UI elements you added look the way you expect them to. If you click the button, it should highlight, and if you click inside the text field, the keyboard should appear. At the moment, though, the button doesnt do anything, the label remains empty, and theres no way to dismiss the keyboard after it appears. To add this functionality, you need to make the appropriate connections between the UI elements and the view controller. These connections are described next. Note: When you run an app in Simulator, you have to click controls that users tap when they run your app on a device.

Create an Action for the Button


As you learned in The Target-Action Pattern Enables Responses to User Interactions (page 22), when the user activates a UI element, the element can send an action message to an object that knows how to perform the corresponding action method (such as add this contact to the users list of contacts). In this tutorial, when the user taps the button, you want it to send a change the greeting message to the view controller. Then, you want the view controller to respond by executing the corresponding change the greeting method, which changes the text thats displayed in the label. Using Xcode, you can add an action to a UI element and set up its corresponding action method by dragging from the element on the canvas to the appropriate source file (typically, a view controllers source file). When you drag from a UI element on the canvas to a source file, you create a connection that is archived in the storyboard file. Later, when the app loads the storyboard file, the connection between the objects is restored.

To add an action for the button . . .


1. If necessary, select MainStoryboard.storyboard in the project navigator to display the scene on the canvas. In the toolbar, click the Utilities button to hide the utilities area and click the assistant editor button to display the Assistant editor pane.

2.

The assistant editor button is the middle Editor button, which looks like this: 3.

Make sure that the Assistant displays the view controllers header file (HelloWorldViewController.h).

Create an Action for the Button


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

37

CHAPTER 4

Configuring the View

4.

Control-drag from the button in the view to the method declaration area in the header file. As you Control-drag, you should see something like this:

When you release the Control-drag, Xcode displays a popover in which you can configure the action connection you just made:

38

Create an Action for the Button


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 4

Configuring the View

5.

In the popover, configure the buttons action connection:


In the Connection pop-up menu, choose Action. In the Name field, enter changeGreeting: (be sure to include the colon). Make sure that the Type field contains id. The id data type can represent any Cocoa object (to learn more about it, see The Dynamism of Objective-C in Cocoa Fundamentals Guide). You want to use id here because it doesnt matter what type of object sends the message.

Make sure that the Event pop-up menu contains Touch Up Inside. You specify the Touch Up Inside event because you want the message to be sent when the user lifts the finger inside the button. (Touch Up Inside corresponds to UIControlEventTouchUpInside.)

Make sure that the Arguments pop-up menu contains Sender.

After you configure the action connection, the popover should look like this:

6.

In the popover, click Connect. Xcode adds a stub implementation of the new changeGreeting: method and indicates that the connection has been made by displaying a filled-in circle to the left of the method:

Create an Action for the Button


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

39

CHAPTER 4

Configuring the View

When you Control-dragged from the button to the HelloWorldViewController.h file and configured the resulting action, you accomplished two things:

You added the appropriate code to the view controller class. Specifically, you added the following action method declaration to the header file:
- (IBAction)changeGreeting:(id)sender;

and the following stub implementation to the implementation file:


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

Note: IBAction is a special keyword that is used only to tell Xcode to treat a method as an action for target-action connections. IBAction is defined to void. The sender parameter in the action method refers to the object that is sending the action message (in this tutorial, the sender is the button).

You created a connection between the button and the view controller. Establishing the connection is the equivalent of invoking addTarget:action:forControlEvents: on the button, with the target being the view controller, the action being the changeGreeting: selector, and the control events containing UIControlEventTouchUpInside.

Next, you create connections between the view controller and the two remaining UI elements (that is, the label and the text field).

Create Outlets for the Text Field and the Label


An outlet is a property that points to another object (typically, an item in a storyboard file). When you create an outlet connection in Xcode, the connection is archived in the storyboard file and restored when the app runs. The restored connection allows the two objects to communicate with each other at runtime. The steps you take to add outlets for the text field and label are very similar to the steps you took when you added the buttons action. Before you start, make sure that the main storyboard file is still visible on the canvas and the HelloWorldViewController header file is still open in the Assistant editor.

40

Create Outlets for the Text Field and the Label


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 4

Configuring the View

To add an outlet for the text field . . .


1. Control-drag from the text field in the view to the method declaration area in the header file. As you Control-drag, you should see something like this:

2.

In the popover that appears when you release the Control-drag, configure the text fields connection:

Make sure that the Connection pop-up menu contains Outlet. In the Name field, enter textField. You can call the outlet whatever you want, but your code is more understandable when an outlet name bears some relationship to the item it represents.

Create Outlets for the Text Field and the Label


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

41

CHAPTER 4

Configuring the View

Make sure that the Type field contains UITextField. Setting the Type field to UITextField ensures that the outlet can only connect to a text field.

Make sure that the Storage pop-up menu contains Weak. The weak storage specifer is appropriate because the text field is a subview of the view controllers view object, and is therefore owned by the view.

After you make these settings, the popover should look like this:

3.

In the popover, click Connect.

You accomplished two things by adding an outlet for the text field:

You added appropriate code to the view controller class. Specifically, you added the following declaration to the header file:
@property (weak, nonatomic) IBOutlet UITextField *textField;

Note: IBOutlet is a special keyword that is used only to tell Xcode to treat the object as an outlet. Its actually defined as nothing so it has no effect at compile time. To the viewDidUnload method you added:
textField = nil;

As its name suggests, the viewDidUnload method is called when your view is unloaded. The viewDidUnload method is also the appropriate place in which to set the view's outlets to nil. Its good programming practice to set to nil an object that no longer exists, because it allows other code to make sure that an object exists before attempting to use it.

You established a connection from the view controller to the text field. Establishing a connection from the view controller does the equivalent of invoking setTextField: on the view controller, passing the text field as the parameter.

42

Create Outlets for the Text Field and the Label


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 4

Configuring the View

Now add an outlet for the label and configure the connection. The steps you follow for this task are the same as the ones you followed to add the outlet for the text field, but with appropriate changes to the configuration.

To add an outlet for the label . . .


1. Control-drag from the label in the view to the method declaration area in the HelloWorldViewController header file in the Assistant editor. In the popover that appears when you release the Control-drag, configure the labels connection:

2.

Make sure that the Connection pop-up menu contains Outlet. In the Name field, enter label. Make sure that the Type field contains UILabel. Make sure that the Storage pop-up menu contains Weak.

3.

In the popover, click Connect.

At this point in the tutorial, youve created a total of three connections to your view controller:

An action connection for the button An outlet connection for the text field An outlet connection for the label

You can verify these connections in the Connections inspector.

To open the Connections inspector for the view controller . . .


1. Click the Standard editor button to switch to the standard editor view.

The Standard editor button is to the left of the Assistant editor button, and it looks like this: 2. 3. 4. Click the Utilities view button to open the utilities area. Select Hello World View Controller in the outline view. Show the Connections inspector in the utilities area. The Connections inspector button is the rightmost inspector button, and it looks like this:

Create Outlets for the Text Field and the Label


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

43

CHAPTER 4

Configuring the View

In the Connections inspector, Xcode displays the connections for the selected object (in this case, the view controller). In your project window, you should see something like this:

Notice that theres a connection between the view controller and its view, in addition to the three connections you created. Xcode provides this default connection between the view controller and its view; you do not have to access it in any way.

Make the Text Fields Delegate Connection


You have one more connection to make in your app: You need to connect the text field to an object that you specify as its delegate. In this tutorial, you use the view controller for the text fields delegate.

44

Make the Text Fields Delegate Connection


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 4

Configuring the View

You need to specify a delegate object for the text field because the text field sends a message to its delegate when the user taps the Return button in the keyboard. In a later step, youll use the method associated with this message to dismiss the keyboard (see Configure the View Controller as the Text Fields Delegate (page 50)). Make sure that the storyboard file is open on the canvas. If its not, select MainStoryboard.storyboard in the project navigator.

To set the text fields delegate . . .


1. In the view, Control-drag from the text field to the yellow sphere in the scene dock (the yellow sphere represents the view controller object). When you release the Control-drag, your project window should look something like this:

Make the Text Fields Delegate Connection


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

45

CHAPTER 4

Configuring the View

2.

Select delegate in the Outlets section of the translucent panel that appears.

Test the Application


Click Run to test your app. You should find that the button highlights when you click it. You should also find that if you click in the text field, the keyboard appears and you can enter text. However, theres still no way to dismiss the keyboard. To do that, you have to implement the relevant delegate method. Youll do that in the next chapter.

Recap
When you configured the view with the appropriate connections you also updated the implementation file to support the outlets and the action. At this point in the tutorial, your HelloWorldViewController.m file should look similar to this (unchanged stub implementations are not shown):
#import "HelloWorldViewController.h" @implementation HelloWorldViewController @synthesize textField; @synthesize label; ... - (void)viewDidUnload { [self setTextField:nil]; [self setLabel:nil]; [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } ... - (IBAction)changeGreeting:(id)sender { } @end

Note that you dont have to use the Xcode feature that automatically adds code when you establish a connection by Control-dragging from the canvas to a source file. Instead, you can add the property and method declarations to the header file yourself, and then make the connections as you did with the text fields delegate. Typically, though, you make fewer mistakes (and have less typing to do) when you let Xcode do as much of the work as it can.

46

Test the Application


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 5

Implementing the View Controller

There are several parts to implementing the view controller: You need to add a property for the users name, implement the changeGreeting: method, and ensure that the keyboard is dismissed when the user taps Done.

Add a Property for the Users Name


You need to declare a variable for the string that holds the users name, and you need to add a property declaration for it so that your code always has a reference to it. You add both declarations to the view controllers header file (that is, HelloWorldViewController.h). At this point in the tutorial, you dont need to make any further changes to the storyboard file. To give yourself more room in which to add the code described in the following steps, hide the utilities area by clicking the Utilities View button again.

To add the variable and property declarations for the users name . . .
1. 2. In the project navigator, select HelloWorldViewController.h. Within the @interface braces, add a variable declaration for the string that will hold the users name. Note that you might have to enter the braces after the @interface statement. After you add the variable declaration, @interface block should look like this:
@interface HelloWorldViewController : UIViewController { NSString *userName; }

3.

After the closing @interface brace and before the @end statement, add an @property statement for the string variable you just declared. The property declaration looks like this:
@property (nonatomic, copy) NSString *userName;

The userName property needs a setter method called setUserName:. Youll provide this method in the next step.

Add a Property for the Users Name


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

47

CHAPTER 5

Implementing the View Controller

To complete the implementation of the userName property, you also need to tell the compiler to synthesize the accessor methods. You provide code to do this in the view controllers implementation file (that is, HelloWorldViewController.m).

To synthesize the accessor methods for the user name property . . .


1. 2. In the project navigator, select HelloWorldViewController.m. After the @implementation HelloWorldViewController line, add the following line of code:
@synthesize userName=_userName;

When you use the @synthesize directive, you tell the compiler to synthesize accessor methods for a property according to the specification that you gave in the interface file. In this tutorial, your declaration of the userName property is @property (nonatomic, copy) NSString *userName;, so the compiler generates two accessor methods:
- (NSString *)userName - (void)setUserName:(NSString *)newUserName

By adding the underscore to userName in your @synthesize code line, you tell the compiler to use _userName as the name of the instance variable for the userName property. Because you didnt declare an instance variable called _userName in your class, this code line also asks the compiler to synthesize that as well. By convention, you prefix the instance variable name with an underscore to remind you that you shouldnt access an instance variable directly. Instead, you should use the accessor methods you synthesized. (An exception to this is that you can get and set an instance variable directly in an init method.) From an academic perspective, avoiding the direct access of instance variables helps preserve encapsulation, but there are also a couple of practical benefits:

Some Cocoa technologies (notably key-value coding) depend on the use of accessor methods, and on the appropriate naming of the accessor methods. If you dont use accessor methods, your application may be less able to take advantage of standard Cocoa features. Some property values are created on-demand. If you try to use the instance variable directly, you may get nil or an uninitialized value. (A view controllers view is a good example of a property value thats created on-demand.)

To help you remember this convention, modify the @synthesize code lines that Xcode added for the text field and label so that they look like this:
@synthesize textField=_textField; @synthesize label=_label;

(If youre interested, you can read more about encapsulation in Storing and Accessing Properties in Cocoa Fundamentals Guide.)

48

Add a Property for the Users Name


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 5

Implementing the View Controller

Implement the changeGreeting: Method


In To add an action for the button (page 37), you configured the button so that when the user taps it, it sends a changeGreeting: message to the view controller. In response, you want the view controller to display in the label the text that the user entered in the text field. Specifically, the changeGreeting: method should: 1. 2. Retrieve the string from the text field and set the view controllers userName property to this string. Create a new string that is based on the userName property and display it in the label.

To implement the changeGreeting: method . . .


1. 2. If necessary, select HelloWorldViewController.m in the project navigator. Complete the stub implementation of the changeGreeting: method by adding the following code:
- (IBAction)changeGreeting:(id)sender { self.userName = self.textField.text; NSString *nameString = self.userName; if ([nameString length] == 0) { nameString = @"World"; } NSString *greeting = [[NSString alloc] initWithFormat:@"Hello, %@!", nameString]; self.label.text = greeting; }

There are several interesting things to note in the changeGreeting: method:

self.userName = self.textField.text; retrieves the text from the text field and sets the view controllers userName property to the result.

In this tutorial, you dont actually use the string that holds the users name anywhere else, but its important to remember its role: Its the very simple model object that the view controller is managing. In general, the controller should maintain information about application data in its own model objectsapplication data shouldnt be stored in user interface elements.

NSString *nameString = self.userName; creates a new variable (of type NSString) and sets it to the view controllers userName property. @"World" is a string constant represented by an instance of NSString. If the user runs your app but does not enter any text (that is, [nameString length] == 0), nameString will contain the string

World .

Implement the changeGreeting: Method


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

49

CHAPTER 5

Implementing the View Controller

The initWithFormat: method creates a new string that follows the format specified by the format string (much like the C printf function with which you might be familiar). In the format string, %@ acts as a placeholder for a string object. All other characters within the double quotation marks of this format string will be displayed onscreen exactly as they appear. (To learn more about strings, see Strings.)

Configure the View Controller as the Text Fields Delegate


If you build and run the application, you should find that when you click the button, the label shows Hello, World! If you select the text field and start typing, though, you should find that you still have no way to indicate that youve finished entering text and dismiss the keyboard. In an iOS application, the keyboard is shown automatically when an element that allows text entry becomes the first responder; it is dismissed automatically when the element loses first responder status. (You can learn more about the first responder by reading The Event-Handling System in iOS App Programming Guide.) Although theres no way to directly message the keyboard, you can make it appear or disappear as a side-effect of toggling the first responder status of a text-entry element. The UITextFieldDelegate protocol includes the textFieldShouldReturn: method that the text field calls when the user taps the Return button (regardless of the actual title of this button). Because you set the view controller as the text fields delegate, you can implement this method to force the text field to lose first responder status by sending it the resignFirstResponder messagewhich has the side-effect of dismissing the keyboard.

To configure HelloWorldViewController as the text fields delegate . . .


1. 2. If necessary, select HelloWorldViewController.m in the project navigator. Implement the textFieldShouldReturn: method. The method should tell the text field to resign first responder status. The implementation might look like this:
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField { if (theTextField == self.textField) { [theTextField resignFirstResponder]; } return YES; }

In this application, its not really necessary to include the theTextField == self.textField test because theres only one text field. This is a good pattern to use, though, because there may be occasions when your object is the delegate of more than one object of the same type and you might need to differentiate between them. 3. Select HelloWorldViewController.h in the project navigator.

50

Configure the View Controller as the Text Fields Delegate


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 5

Implementing the View Controller

4.

In the @interface line, just before the opening brace, add <UITextFieldDelegate> after UIViewController. Your interface declaration should look like this:
@interface HelloWorldViewController : UIViewController <UITextFieldDelegate> { ...

This declaration specifies that your HelloWorldViewController class adopts the UITextFieldDelegate protocol.

Test the Application


Build and run the application. This time, everything should behave as you expect. In Simulator, click Done to dismiss the keyboard after you have entered your name, and then click the Hello button to display Hello, Your Name! in the label. If the app doesnt behave as you expect, you need to troubleshoot (for some areas to investigate, see Troubleshooting (page 53)).

Recap
Now that youve finished the implementation of the view controller, youve completed your first iOS application. Congratulations! Take a moment to think about how the view controller fits into the overall application architecture. You will use view controllers in all iOS applications you write.

Test the Application


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

51

CHAPTER 5

Implementing the View Controller

52

Recap
2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 6

Troubleshooting

If you have trouble getting your application to work correctly, try the problem-solving approaches described in this chapter.

Code and Compiler Warnings


If things arent working as they should, first compare your code with the complete listings in Code Listings (page 57). Your code should compile without any warnings. If you do receive warnings, its recommended that you treat them as very likely to be errors. The reason for this is that Objective-C is a very flexible language, so that sometimes the most you get from the compiler is a warning.

Check the Storyboard File


As a developer, if things dont work correctly, your natural instinct is probably to check your source code for bugs. But when you use Cocoa, another dimension is added. Much of your applications configuration may be encoded in the storyboard file. For example, if you havent made the correct connections, your application wont behave as you expect.

If the text doesnt update when you click the button, it might be that you didnt connect the buttons action to the view controller, or that you didnt connect the view controllers outlets to the text field or label. If the keyboard does not disappear when you click Done, you might not have connected the text fields delegate or connected the view controllers textField outlet to the text field (see Make the Text Fields Delegate Connection (page 44)). If you have connected the delegate, there might be a more subtle problem (see Delegate Method Names (page 53)).

Delegate Method Names


A common mistake with delegates is to misspell the delegate method name. Even if youve set the delegate object correctly, if the delegate doesnt use the right name in its method implementation, the correct method wont be invoked. Its usually best to copy and paste delegate method declarations, such as textFieldShouldReturn:, from the documentation.

Code and Compiler Warnings


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

53

CHAPTER 6

Troubleshooting

54

Delegate Method Names


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

CHAPTER 7

Next Steps

In this tutorial, you created a very simple iOS application. Cocoa Touch offers a rich development environment, though, and this tutorial only scratches the surface. This chapter suggests some directions you might take next as you continue to learn about iOS app development.

Improve the User Interface


iOS users have high expectations for the look and feel of the apps they run on their iOS-based devices. As you work on improving the UI of your app, consider adding images and color to the UI elements, or a background image to the view. One way to find out about different ways to configure a UI element is to drag it from the object library into a view on the canvas and then look at its configurable attributes in the Attributes inspector. Many iPhone applications support multiple orientations; applications for iPad should support all orientations. Another way to improve the UI of your app is to make sure that your view controller can handle changes in orientation. To support different orientations, first learn about the shouldAutorotateToInterfaceOrientation: method. Then, in your storyboard file, adjust the UI to ensure that all the UI elements are properly positioned when the view is rotated. Be sure to read iOS Human Interface Guidelines to learn about the recommended ways to design the user interface and user experience of your app.

Install the Application on a Device


If you have a suitable device connected to your computer via its 30-pin USB cable, and you have a valid certificate from the iOS Developer Program, set the active SDK for your project to iPhone Device (instead of iOS Simulator) and build and run the project. Assuming your code compiles successfully, Xcode then automatically uploads the app to your device. To learn more about this part of the development process, see App Development Overview.

Add More Functionality


You can also try expanding the apps functionality. Here are some of the many directions in which you can go:

Write a custom view. Rather than using a view as a canvas on which to drop prebuilt user interface controls, you might try writing a custom view that draws its own content or responds to touch events. For inspiration, look at sample code projects such as MoveMe and Metronome.

Improve the User Interface


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

55

CHAPTER 7

Next Steps

Use a table view. Although you used Xcode to lay out the user interface for this application, many applications use table views to lay out the interface. This makes it easy to create an interface that extends beyond the bounds of the screenallowing the user to scroll to reveal additional elements. You should first investigate how to create a simple list using a table view. There are several sample code projects, such as TableViewSuite, that you can use as a foundation for a custom app. Use a navigation controller. Navigation controllers and tab bar controllers provide different ways to organize an iOS app. Navigation controllers often work in conjunction with table views, but both navigation controllers and tab bar controllers work together with view controllers. Take a look at some of the sample code projectssuch as SimpleDrillDownthat use navigation controllers and expand on them to create your own applications. Localize your app. You can often increase the size of your potential market by localizing your application. Internationalization is the process of making your application localizable. To learn more about internationalization, read Internationalization Programming Topics. Optimize your code. High performance is critical to a good user experience on iOS. You should learn to use the various performance tools provided with Xcodein particular Instrumentsto tune your application so that it minimizes its resource requirements.

The most important thing is to try out new ideas and to experiment. There are many code samples you can look at for inspiration, and the documentation will help you to understand concepts and programming interfaces.

Add Unit Tests


When you created the project for this tutorial, you didnt select the option to add support for unit tests. As you develop real apps, its important to incorporate testing. In some respects, you can think of testing as the counterpart of the design principle of encapsulation: Testing ensures that if the implementation of a method changes, the method still works as advertised. When you add testing to your app, you can either create a new version of the project that sets up unit testing from the start, or you can use the current project and choose File > New > New Target, select the Other category, and then select the template Cocoa Unit Testing Bundle. Examine your project to see what Xcode adds when you incorporate unit testing. To learn about unit testing, see Unit Testing Applications.

56

Add Unit Tests


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

APPENDIX A

Code Listings

This appendix provides listings for the interface and implementation files of the HelloWorldViewController class. The listings dont show comments and other method implementations from the file templates.

The Interface file: HelloWorldViewController.h


#import <UIKit/UIKit.h> @interface HelloWorldViewController : UIViewController <UITextFieldDelegate> { NSString *userName; } @property (weak, nonatomic) IBOutlet UITextField *textField; @property (weak, nonatomic) IBOutlet UILabel *label; @property (nonatomic, copy) NSString *userName; - (IBAction)changeGreeting:(id)sender; @end

The Implementation File: HelloWorldViewController.m


#import "HelloWorldViewController.h" @implementation HelloWorldViewController @synthesize textField=_textField; @synthesize label=_label; @synthesize userName=_userName;

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField { if (theTextField == self.textField) { [theTextField resignFirstResponder]; } return YES; } - (IBAction)changeGreeting:(id)sender { self.userName = self.textField.text; NSString *nameString = self.userName; if ([nameString length] == 0) { nameString = @"World";

The Interface file: HelloWorldViewController.h


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

57

APPENDIX A

Code Listings

} NSString *greeting = [[NSString alloc] initWithFormat:@"Hello, %@!", nameString]; self.label.text = greeting; } @end

58

The Implementation File: HelloWorldViewController.m


2011-10-12 | 2011 Apple Inc. All Rights Reserved.

REVISION HISTORY

Document Revision History

This table describes the changes to Your First iOS App. Date 2011-10-12 2011-06-06 2011-03-08 2010-10-12 2010-07-01 2010-03-15 2009-10-08 2009-08-10 Notes Updated to use storyboards and ARC. Corrected typographical errors. Updated for Xcode 4. Corrected a bad link. Updated for iOS 4. Updated for iOS 3.2. Emphasized need to connect text field in Interface Builder. Removed a reference to dot syntax for an example that used an accessor method directly. Updated for iOS 3.0. Corrected typographical errors. Clarified description of the target-action design pattern. Minor corrections and clarifications. New document that introduces application development for iPhone.

2009-06-15 2009-01-06 2008-10-15 2008-09-09 2008-06-09

59
2011-10-12 | 2011 Apple Inc. All Rights Reserved.

REVISION HISTORY

Document Revision History

60
2011-10-12 | 2011 Apple Inc. All Rights Reserved.

Potrebbero piacerti anche