您的位置:首页 > 移动开发

Your First iOS App

2018-03-27 22:47 483 查看
Your First iOS App
Contents
About Creating Your First iOS App 4
At a Glance 5
Becoming Familiar with the Tools and the Design Patterns 5
Learning About the Roles of View Controllers and Views 5
Writing Code to Perform a Custom Task 6
Solving Problems and Choosing Your Next Steps 6
See Also 6
Getting Started 7
Create and Test a New Project 7
Find Out How an Application Starts Up 13
Recap 19
Understanding Fundamental Design Patterns 20
Cocoa Touch Provides the Frameworks You Need for iOS App Development 20
Delegation Helps You Add Functionality Without Subclassing 20
Model-View-Controller Makes Code Easier to Write and Reuse 21
The Target-Action Pattern Enables Responses to User Interactions 22
Other Design Patterns 22
Inspecting the View Controller and Its View 23
Use the Inspector to Examine the View Controller 23
Change the View’s Background Color 26
Recap 29
Configuring the View 30
Add the User Interface Elements 30
Create an Action for the Button 34
Create Outlets for the Text Field and the Label 38
Make the Text Field’s Delegate Connection 43
Test the Application 44
Recap 45
Implementing the View Controller 46
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
2
Add a Property for the User’s Name 46
Implement the changeGreeting: Method 48
Configure the View Controller as the Text Field’s Delegate 49
Test the Application 50
Recap 51
Troubleshooting 52
Code and Compiler Warnings 52
Check the Storyboard File 52
Delegate Method Names 53
Next Steps 54
Improve the User Interface 54
Install the Application on a Device 54
Add More Functionality 54
Add Unit Tests 55
Code Listings 56
The Interface file: HelloWorldViewController.h 56
The Implementation File: HelloWorldViewController.m 56
Document Revision History 58
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
3
Contents
Your First iOS Application introduces you to the Three T’s 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, you’ll have an app that accepts your input and prints it on the
screen:
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
4
About Creating Your First iOS App
Tobenefitfromthistutorial,youmustalreadyhavesomefamiliaritywiththebasicsofcomputerprogramming
ingeneralandwiththe Objective-C languageinparticular.Ifyouhaven’tusedObjective-Cbefore,readLearning
Objective-C: A Primer before you begin this tutorial.
Note YoucanusethistutorialtogetstartedwithiOSappdevelopmentevenifyouintendtodevelop
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, Apple’s 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 “GettingStarted” (page 7),“UnderstandingFundamentalDesignPatterns” (page
20)
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,anditcancontainotherviewobjects,suchasbuttonsorimages.Aviewcontrollerisanobjectthatcontrols
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.
About Creating Your First iOS App
At a Glance
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
5
Relevant chapters “Understanding Fundamental Design Patterns” (page 20), “Inspecting the View
Controller and Its View” (page 23), “Configuring the View” (page 30)
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.
Relevant chapter “Implementing the View Controller” (page 46)
Solving Problems and Choosing Your Next Steps
As you complete the tasks in this tutorial, you might encounter problems that you don’t 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 52), “Code Listings” (page 56), “Next Steps” (page 54)
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 can’t help you decide what your apps should do, and
it doesn’t 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 ar
19262
e 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
Developing for the App Store.
About Creating Your First iOS App
See Also
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
6
To create the iOS application in this tutorial, you need Xcode 4.2. Xcode is Apple’s 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 don’t 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 it’s in /Developer/Applications ).
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
7
Getting Started
If you’ve never created or opened a project in Xcode before, you should see a Welcome to Xcode
window similar to this:
If you’ve 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).
Getting Started
Create and Test a New Project
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
8
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.
3. In the iOS section at the left side of the dialog, select Application.
4. In the main area of the dialog, select Single View Application and then click Next.
Getting Started
Create and Test a New Project
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
9
A new dialog appears that prompts you to name your application and choose additional options for
your project.
5. Fill in the Product Name, Company Identifier, and Class Prefix fields.
You can use the following values:

Product Name: HelloWorld

CompanyIdentifier:Yourcompanyidentifier,ifyouhaveone.Ifyoudon’thaveacompanyidentifier,
you can use edu.self .

Class Prefix: HelloWorld
Note Xcode uses the product name you entered to name your project and the application.
Xcodeusestheclassprefixnameyouenteredtonametheclassesitcreatesforyou.Forexample,
Xcode automatically creates an application delegate class and names it
HelloWorldAppDelegate .Ifyouenteradifferentvaluefortheclassprefix,thentheapplication
delegate class is named YourClassPrefixName AppDelegate .
To keep things simple, this tutorial assumes that you named your product HelloWorld and
that you used HelloWorld for the class prefix value.
Getting Started
Create and Test a New Project
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
10
6. In the Device Family pop-up menu, make sure that iPhone is selected.
7. 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).
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:
Getting Started
Create and Test a New Project
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
11
Even though you haven’t 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.
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.
Getting Started
Create and Test a New Project
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
12
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 iPhonescreen, Simulator opens your application, which should look like this:
Rightnow,yourapplicationisnotveryinteresting:itsimplydisplaysablankwhitescreen.Tounderstandwhere
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 don’t 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
tothewindowserver,establishestherunloop,andsoon.Mostofthisworkisdonebythe UIApplicationMain
function, which is called in the main.m source file.
Getting Started
Find Out How an Application Starts Up
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
13
To look at the main.m source file . . .
1. Open the Supporting Files folder in the project navigator by clicking the disclosure triangle next to it.
2. Select main.m .
Xcode opens the source file in the main editor area of the window, which should look similar to this:
The main function in main.m calls the UIApplicationMain function within an autorelease pool:
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([HelloWorldAppDelegate
class]));
}
Getting Started
Find Out How an Application Starts Up
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
14
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 app’s content is drawn.
The call to UIApplicationMain also scans the application’s Info.plist file. The Info.plist file is a
property list that contains information about the application such as its name and icon.
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:
Getting Started
Find Out How an Application Starts Up
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
15
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 application’s 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.
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 objects—that is,
the area that looks like graph paper—is called the canvas.)
Getting Started
Find Out How an Application Starts Up
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
16
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.
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
ofafewitemsthataredisplayedintheXcodeoutlineview(whichisthepanethatappearsbetweenthecanvas
and the project navigator):
Getting Started
Find Out How an Application Starts Up
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
17
 ●
A first responder placeholder object (represented by an orange cube).
Thefirstresponderisadynamicplaceholderthatrepresentstheresponderobjectthatfirstreceivesevents
such as keyboard events, motion events, and action messages (you’ll learn more about action messages
in “The Target-Action Pattern Enables Responses to User Interactions” (page 22)). You won’t 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).
Whenasceneinastoryboardfileisloaded,itcreatesaninstanceoftheviewcontrollerclassthatmanages
it.

A view (which is listed below the view controller—you 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 controller’s 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).

Instantiatesthestoryboard’sinitialviewcontrollerandassignsitasthewindowobject’srootviewcontroller.
When the application object has completed these tasks, it sends its delegate an
application:didFinishLaunchingWithOptions: message.Thismessagegivesthedelegateanopportunity
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 it’s 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 20).
Getting Started
Find Out How an Application Starts Up
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
18
Recap
In this chapter you used Xcode to create a new project based on the Single View template. Then, you built and
ranthedefaultapplicationthatthetemplatedefines.Youalsolookedatsomeofthebasicpiecesoftheproject,
such as the main.m source file, the Info.plist file, and the storyboard file, and learned how an application
startsup.Inthenextchapter,you’lllearnaboutthedesignpatternsthatpervadeiOSapplicationdevelopment
and how they apply to your app.
Getting Started
Recap
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
19
Before you start customizing your app, take a moment to learn about the programming environment you’re
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,
you’ll 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
MacOSXapps).AsyoudevelopappsforiOS,includingtheappinthistutorial,you’llrelyontheobject-oriented
frameworks that Cocoa Touch provides. In particular, you’ll 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.
Ifaclassconformsto(oradopts)aprotocol,itguaranteesthatitimplementstherequiredmethodsofaprotocol.
(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” .
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
20
Understanding Fundamental Design Patterns
The application in this tutorial uses delegation in two ways:

Every iOS app must have an application delegate object; in this app, it’s an instance of the
HelloWorldAppDelegate class that’s provided by the Single View template.
Inadditiontoperformingcustomconfigurationtasks,theappdelegatecanhandleapplication-levelevents
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 you’ll be adding later needs to tell its delegate when the user is finished typing.
Tohelpaccomplishthis,youensurethattheviewcontrollerobject(thatis, 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 simple—it’s just a string that holds the name the user enters.
Because this string is used in only one method, it’s not strictly necessary to identify it as a model object, but
treating it as such helps you become comfortable with the MVC design pattern.
Viewobjectsknowhowtodisplaydata(representedbymodelobjects)andcanallowtheusertoeditthedata.
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(themodel),andupdatesthelabel(anotherview).Theupdateisinitiatedasaresultofanactionmessage
sent by the button.
Understanding Fundamental Design Patterns
Model-View-Controller Makes Code Easier to Write and Reuse
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
21
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
messageinresponsetoauser-initiatedevent,suchasatap.Forexample,consideranappthatstorestheuser’s
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 user’s input.
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 you’ve 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.
Understanding Fundamental Design Patterns
The Target-Action Pattern Enables Responses to User Interactions
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
22
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 controller’s 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, it’s 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. Ifnecessary,click MainStoryboard.storyboard intheprojectnavigatortodisplaythesceneonthe
canvas.
2. In the outline view, select Hello World View Controller (it’s listed below First Responder).
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
23
Inspecting the View Controller and Its View
Your project window should look something like this:
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. Click the rightmost View control in the toolbar to display the utilities area at the right side of the
window.
4. Click the Attributes inspector button at the top of the utilities area (it’s the fourth button from the left
and it looks like this: ).
Inspecting the View Controller and Its View
Use the Inspector to Examine the View Controller
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
24
Your project window should look something like this (you might have to resize the Xcode window to
see everything):
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.
Inspecting the View Controller and Its View
Use the Inspector to Examine the View Controller
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
25
Change the View’s Background Color
In “Find Out How an Application Starts” (page 13), 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 controller’s view . . .
1. In the outline view, click the disclosure triangle next to Hello World View Controller (if it’s not already
open) and select View.
Xcode highlights the view area on the canvas.
2. Click the Attributes button at the top of the utilities area to open the Attributes inspector, if it’s not
already open.
3. 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.
Inspecting the View Controller and Its View
Change the View’s Background Color
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
26
Your project window should look something like this:
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.
Inspecting the View Controller and Its View
Change the View’s Background Color
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
27
Test your application in Simulator. You should see something like this:
Tip You don’t 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 you’ve made changes.
Before you continue with the tutorial, restore the view’s background color to white.
To restore the view’s 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. In the Background pop-up menu, choose the white square listed in the Recently Used Colors section
of the menu.
Inspecting the View Controller and Its View
Change the View’s Background Color
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
28
3. Click the Run button to compile and run your app (and save your changes).
After you’ve 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 won’t
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.
Inspecting the View Controller and Its View
Recap
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
29
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 view—now 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.
2. If necessary, open the object library.
The object library appears at the bottom of the utilities area. If you don’t see it, you can click the object
library button, which looks like this: .
3. 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 control’s name and
appearance, and a short description of its function.
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
30
Configuring the View
4. One at a time, drag a text field, a round rect button, and a label from the list to 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 element’s resize
handles, select it (that is, click it once).
Configuring the View
Add the User Interface Elements
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
31
Youcanlayoutyourapp’suserinterfaceanywayyouchoose,butthistutorialusesthefollowinglayout:
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 .
7. In the Text Field Attributes inspector, click the middle Alignment button to center the text field’s text.
8. In the Label Attributes inspector, click the middle Alignment button to center the label’s text.
9. In the view, double-click the button and enter the text Hello .
Configuring the View
Add the User Interface Elements
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
32
After you add the text field, label, and button and make the other recommended changes, your project should
look similar to this:
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 user’s
task. You make all of these configuration changes in the Attributes inspector.
Configuring the View
Add the User Interface Elements
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
33
To configure the text field . . .
1. In the view, select the text field.
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 doesn’t do anything, the label remains empty, and there’s no way to dismiss
thekeyboardafteritappears.Toaddthisfunctionality,youneedtomaketheappropriateconnectionsbetween
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
thecorrespondingactionmethod(suchas“addthiscontacttotheuser’slistofcontacts”).Inthistutorial,when
the user taps the button, you want it to send a “change the greeting” message to the view controller. Then,
youwanttheviewcontrollertorespondbyexecutingthecorresponding“changethegreeting”method,which
changes the text that’s 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 controller’s 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.
2. In the toolbar, click the Utilities button to hide the utilities area and click the assistant editor button to
display the Assistant editor pane.
Configuring the View
Create an Action for the Button
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
34
The assistant editor button is the middle Editor button, which looks like this: .
3. MakesurethattheAssistantdisplaystheviewcontroller’sheaderfile( HelloWorldViewController.h ).
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:
Configuring the View
Create an Action for the Button
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
35
When you release the Control-drag, Xcode displays a popover in which you can configure the action
connection you just made:
5. In the popover, configure the button’s 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 doesn’t 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:
Configuring the View
Create an Action for the Button
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
36
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:
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:
onthebutton,withthetargetbeingtheviewcontroller,theactionbeingthe changeGreeting: selector,
and the control events containing UIControlEventTouchUpInside .
Next,youcreateconnectionsbetweentheviewcontrollerandthetworemainingUIelements(thatis,thelabel
and the text field).
Configuring the View
Create an Action for the Button
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
37
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
addedthebutton’saction.Beforeyoustart,makesurethatthemainstoryboardfileisstillvisibleonthecanvas
and the HelloWorldViewController header file is still open in the Assistant editor.
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.
Configuring the View
Create Outlets for the Text Field and the Label
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
38
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 field’s 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.

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.
Configuring the View
Create Outlets for the Text Field and the Label
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
39
Theweakstoragespeciferisappropriatebecausethetextfieldisasubviewoftheviewcontroller’s
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. It’s 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 . It’s 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.
Configuring the View
Create Outlets for the Text Field and the Label
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
40
Now add an outlet for the label and configure the connection. The steps you follow for this task are the same
astheonesyoufollowedtoaddtheoutletforthetextfield,butwithappropriatechangestotheconfiguration.
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.
2. In the popover that appears when you release the Control-drag, configure the label’s connection:

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, you’ve 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. Click the Utilities view button to open the utilities area.
3. Select Hello World View Controller in the outline view.
4. Show the Connections inspector in the utilities area.
The Connections inspector button is the rightmost inspector button, and it looks like this:
Configuring the View
Create Outlets for the Text Field and the Label
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
41
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 there’s a connection between the view controller and its view, in addition to the three connections
youcreated.Xcodeprovidesthisdefaultconnectionbetweentheviewcontrolleranditsview;youdonothave
to access it in any way.
Configuring the View
Create Outlets for the Text Field and the Label
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
42
Make the Text Field’s 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 field’s delegate.
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, you’ll use the method associated with
this message to dismiss the keyboard (see “Configure the View Controller as the Text Field’s Delegate” (page
49)).
Make sure that the storyboard file is open on the canvas. If it’s not, select MainStoryboard.storyboard in
the project navigator.
To set the text field’s 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).
Configuring the View
Make the Text Field’s Delegate Connection
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
43
When you release the Control-drag, your project window should look something like this:
2. Select delegate in the Outlets section of the translucent panel that appears.
Test the Application
Click Run to test your app.
Configuring the View
Test the Application
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
44
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, there’s still no way to dismiss the keyboard. To
do that, you have to implement the relevant delegate method. You’ll 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
Notethatyoudon’thavetousetheXcodefeaturethatautomaticallyaddscodewhenyouestablishaconnection
byControl-draggingfromthecanvastoasourcefile.Instead,youcanaddthepropertyandmethoddeclarations
to the header file yourself, and then make the connections as you did with the text field’s 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.
Configuring the View
Recap
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
45
There are several parts to implementing the view controller: You need to add a property for the user’s name,
implement the changeGreeting: method, and ensure that the keyboard is dismissed when the user taps
Done.
Add a Property for the User’s Name
You need to declare a variable for the string that holds the user’s name, and you need to add a property
declarationforitsothatyourcodealwayshasareferencetoit.Youaddbothdeclarationstotheviewcontroller’s
header file (that is, HelloWorldViewController.h ).
At this point in the tutorial, you don’t 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 user’s name . . .
1. In the project navigator, select HelloWorldViewController.h .
2. Within the @interface braces, add a variable declaration for the string that will hold the user’s 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;
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
46
Implementing the View Controller
The userName property needs a setter method called setUserName: . You’ll provide this method in the
next step.
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 controller’s implementation file (that is,
HelloWorldViewController.m ).
To synthesize the accessor methods for the user name property . . .
1. In the project navigator, select HelloWorldViewController.m .
2. After the @implementation HelloWorldViewController line, add the following line of code:
@synthesize userName=_userName;
Whenyouusethe @synthesize directive,youtellthecompilertosynthesizeaccessormethodsforaproperty
accordingtothespecificationthatyougaveintheinterfacefile.Inthistutorial,yourdeclarationofthe userName
property is @property (nonatomic, copy) NSString *userName; , so the compiler generates two
accessor methods:
- (NSString *)userName
- (void)setUserName:(NSString *)newUserName
Byaddingtheunderscoreto userName inyour @synthesize codeline,youtellthecompilertouse _userName
asthenameoftheinstancevariableforthe userName property.Becauseyoudidn’tdeclareaninstancevariable
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 shouldn’t
accessaninstancevariabledirectly.Instead,youshouldusetheaccessormethodsyousynthesized.(Anexception
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 don’t 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 controller’s view is a good example of a property value that’s created
on-demand.)
Implementing the View Controller
Add a Property for the User’s Name
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
47
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 you’re interested, you can read more about encapsulation in “Storing and Accessing Properties” in Cocoa
Fundamentals Guide.)
Implement the changeGreeting: Method
In “To add an action for the button” (page 34), you configured the button so that when the user taps it, it
sendsa changeGreeting: messagetotheviewcontroller.Inresponse,youwanttheviewcontrollertodisplay
in the label the text that the user entered in the text field. Specifically, the changeGreeting: method should:
1. Retrieve the string from the text field and set the view controller’s userName property to this string.
2. Create a new string that is based on the userName property and display it in the label.
To implement the changeGreeting: method . . .
1. If necessary, select HelloWorldViewController.m in the project navigator.
2. 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;
}
Implementing the View Controller
Implement the changeGreeting: Method
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
48
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
controller’s userName property to the result.
Inthistutorial,youdon’tactuallyusethestringthatholdstheuser’snameanywhereelse,butit’simportant
to remember its role: It’s 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 objects—application
data shouldn’t be stored in user interface elements.

NSString *nameString = self.userName; creates a new variable (of type NSString ) and sets it
to the view controller’s userName property.

@"World" isastringconstantrepresentedbyaninstanceof NSString .Iftheuserrunsyourappbutdoes
not enter any text (that is, [nameString length] == 0 ), nameString will contain the string “World”.

The initWithFormat: methodcreatesanewstringthatfollowstheformatspecifiedbytheformatstring
(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 Field’s Delegate
If you build and run the application, you should find that when you click the button, the label shows “Hello,
World!”Ifyouselectthetextfieldandstarttyping,though,youshouldfindthatyoustillhavenowaytoindicate
that you’ve 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
moreaboutthefirstresponderbyreading “TheEvent-HandlingSystem” iniOSAppProgrammingGuide.)Although
there’s 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 field’s delegate, you can implement this method to force the text field to lose first
responderstatusbysendingitthe resignFirstResponder message—whichhastheside-effectofdismissing
the keyboard.
To configure HelloWorldViewController as the text field’s delegate . . .
1. If necessary, select HelloWorldViewController.m in the project navigator.
Implementing the View Controller
Configure the View Controller as the Text Field’s Delegate
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
49
2. 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, it’s not really necessary to include the theTextField == self.textField test
becausethere’sonlyonetextfield.Thisisagoodpatterntouse,though,becausetheremaybeoccasions
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.
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 doesn’t behave as you expect, you need to troubleshoot (for some areas to investigate, see
“Troubleshooting” (page 52)).
Implementing the View Controller
Test the Application
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
50
Recap
Nowthatyou’vefinishedtheimplementationoftheviewcontroller,you’vecompletedyourfirstiOSapplication.
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.
Implementing the View Controller
Recap
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
51
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 aren’t working as they should, first compare your code with the complete listings in “Code
Listings” (page 56).
Your code should compile without any warnings. If you do receive warnings, it’s 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 don’t 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 application’s configuration may be
“encoded” in the storyboard file. For example, if you haven’t made the correct connections, your application
won’t behave as you expect.

If the text doesn’t update when you click the button, it might be that you didn’t connect the button’s
action to the view controller, or that you didn’t connect the view controller’s outlets to the text field or
label.

If the keyboard does not disappear when you click Done, you might not have connected the text field’s
delegate or connected the view controller’s textField outlet to the text field (see “Make the Text Field’s
Delegate Connection” (page 43)). If you have connected the delegate, there might be a more subtle
problem (see “Delegate Method Names” (page 53)).
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
52
Troubleshooting
Delegate Method Names
A common mistake with delegates is to misspell the delegate method name. Even if you’ve set the delegate
object correctly, if the delegate doesn’t use the right name in its method implementation, the correct method
won’t be invoked. It’s usually best to copy and paste delegate method declarations, such as
textFieldShouldReturn: , from the documentation.
Troubleshooting
Delegate Method Names
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
53
Inthistutorial,youcreatedaverysimpleiOSapplication.CocoaTouchoffersarichdevelopmentenvironment,
though,andthistutorialonlyscratchesthesurface.Thischaptersuggestssomedirectionsyoumighttakenext
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
Developing for the App Store.
Add More Functionality
You can also try expanding the app’s functionality. Here are some of the many directions in which you can go:
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
54
Next Steps
 ●
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.

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 screen—allowing the user to scroll to reveal additional elements. You should
firstinvestigatehowtocreateasimplelistusingatableview.Thereareseveralsamplecodeprojects,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
organizeaniOSapp.Navigationcontrollersoftenworkinconjunctionwithtableviews,butbothnavigation
controllers and tab bar controllers work together with view controllers. Take a look at some of the sample
code projects—such as SimpleDrillDown—that 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
usethevariousperformancetoolsprovidedwithXcode—inparticularInstruments—totuneyourapplication
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
lookatforinspiration,andthedocumentationwillhelpyoutounderstandconceptsandprogramminginterfaces.
Add Unit Tests
When you created the project for this tutorial, you didn’t select the option to add support for unit tests. As you
develop real apps, it’s 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
fromthestart,oryoucanusethecurrentprojectandchooseFile>New>NewTarget,selecttheOthercategory,
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” .
Next Steps
Add Unit Tests
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
55
Thisappendixprovideslistingsfortheinterfaceandimplementationfilesofthe HelloWorldViewController
class. The listings don’t 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;
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
56
CodeListings
- (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";
}
NSString *greeting = [[NSString alloc] initWithFormat:@"Hello, %@!", nameString];
self.label.text = greeting;
}
@end
Code Listings
The Implementation File: HelloWorldViewController.m
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
57
This table describes the changes to Your First iOS App.
Notes Date
Updated to use storyboards and ARC. 2011-10-12
Corrected typographical errors. 2011-06-06
Updated for Xcode 4. 2011-03-08
Corrected a bad link. 2010-10-12
Updated for iOS 4. 2010-07-01
Updated for iOS 3.2. 2010-03-15
Emphasized need to connect text field in Interface Builder. 2009-10-08
Removed a reference to dot syntax for an example that used an accessor
method directly.
2009-08-10
Updated for iOS 3.0. 2009-06-15
Corrected typographical errors. 2009-01-06
Clarified description of the target-action design pattern. 2008-10-15
Minor correctionsand clarifications. 2008-09-09
New document that introduces application development for iPhone. 2008-06-09
2011-10-12 | © 2011 Apple Inc. All Rights Reserved.
58
Document Revision History
Apple Inc.
© 2011 Apple Inc.
All rights reserved.
No part of this publication may be reproduced,
storedinaretrievalsystem,ortransmitted,inany
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
Apple’s copyright notice.
The Apple logo is a trademark of Apple Inc.
No licenses, express or implied, are granted with
respecttoanyofthetechnologydescribedinthis
document.Appleretainsallintellectualproperty
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.
iPadis 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.ASARESULT,THISDOCUMENTISPROVIDED
“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,ORCONSEQUENTIAL
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
youspecificlegalrights,andyoumayalsohaveother
rights which vary from state to state.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: