This tutorial takes you through the process of creating a simple user interface and adding the custom behavior that transforms the interface into a working app. The finished app will run on iPhone and iPad.
This tutorial teaches you how to:
Use Xcode to create and manage a project
Identify the key pieces of an Xcode project
Run your app in iOS Simulator
Create a basic user interface in a storyboard
Preview your user interface
Adopt Auto Layout to add flexibility to your user interface
After you complete all the steps in this tutorial, you’ll have an app that looks something like this:
These tutorials use Xcode 6.1.1 and iOS SDK 8.1, so if you’re following along using other software versions, you might notice some differences.
Create a New Project
Xcode includes several built-in app templates for developing common types of iOS apps, such as games, apps with tab-based navigation, and table-view-based apps. Most of these templates have preconfigured interface and source code files. For this tutorial, you’ll start with the most basic template: Single View Application.
Working with the Single View Application template helps you understand the basic structure of an iOS app and how content gets onscreen. After you learn how everything works, you can use one of the other templates for your own app.
To create a new project
Open Xcode from the
The Xcode welcome window appears.
If a project window appears instead of the welcome window, don’t worry—you probably created or opened a project in Xcode previously. Just use the menu item in the next step to create the project.
In the welcome window, click “Create a new Xcode project” (or choose File > New > Project).
Xcode opens a new window and displays a dialog in which you choose a template.
In the iOS section at the left of the dialog, select Application.
In the main area of the dialog, click Single View Application and then click Next.
In the dialog that appears, name your app and choose additional options for your project.
Use the following values:
Xcode uses the product name you entered to name your project and the app.
Organization Name: The name of your organization or your own name. You can leave this blank.
Organization Identifier: Your organization identifier, if you have one. If you don’t, use
Bundle Identifier: This value is automatically generated based on your product name and organization identifier.
A Universal app is one that runs on both iPhone and iPad.
Use Core Data: Leave unselected.
In the dialog that appears, choose a location to save your project and click Create.
Xcode opens your new project in a window (called the workspace window):
You might notice a warning message that says “No signing identity found.” This warning means you haven’t set up Xcode for iOS development yet, but you can complete the tutorial without doing it. At the end of this document, there’s a link to a guide that helps you set up Xcode to continue iOS development.
Get Familiar with Xcode
Xcode includes everything you need to create an app. It not only organizes the files that go into creating an app, it provides editors for code and interface elements, allows you to build and run your app, and includes a powerful integrated debugger.
Take a few moments to familiarize yourself with the Xcode workspace. You’ll use the controls identified in the window below throughout this tutorial. Click different buttons to get a feel for how they work. If you want more information on part of the interface, read the help articles for it—to find them, Control-click an area of Xcode and choose the article from the shortcut menu that appears.
Run iOS Simulator
Because you based your project on an Xcode template, the basic app environment is automatically set up for you. Even though you haven’t written any code, you can build and run the Single View Application template without any additional configuration.
To build and run your app, use the iOS Simulator app that’s included in Xcode. As its name implies, iOS Simulator gives you an idea of how your app would look and behave if it were running on an iOS device.
iOS Simulator can model a number of different types of hardware—iPad, iPhone with different screen sizes, and so on—so you can simulate your app on every device you’re developing for. In this tutorial, use the iPhone 6 option.
To run your app in iOS Simulator
Make sure iPhone 6 is selected in the Scheme pop-up menu in the Xcode toolbar.
Go ahead and look through the menu to see what other hardware options are available in iOS Simulator.
Click the Run button, located in the top-left corner of the Xcode toolbar.
Alternatively, choose Product > Run (or press Command-R).
If you’re running an app for the first time, Xcode asks whether you’d like to enable developer mode on your Mac. Developer mode allows Xcode access to certain debugging features without requiring you to enter your password each time. Decide whether you’d like to enable developer mode and follow the prompts. If you choose not to enable it, you may be asked for your password later on. The tutorial assumes developer mode is enabled.
Watch the Xcode toolbar as the build process completes.
Xcode displays messages about the build process in the activity viewer, which is in the middle of the toolbar.
After Xcode finishes building your project, iOS Simulator starts automatically. It may take a few moments to start up the first time.
iOS Simulator opens in iPhone mode, just as you specified. On the simulated iPhone screen, iOS Simulator launches your app. Before the app finishes launching, you’ll see a launch screen with your app’s name, ToDoList.
Then, you should see something like this:
Right now, the Single View Application template doesn’t do much—it just displays a white screen. Other templates have more complex behavior. It’s important to understand a template’s uses before you extend it to make your own app. Running your app in iOS Simulator with no modifications is a good way to start developing that understanding.
Quit iOS Simulator by choosing iOS Simulator > Quit iOS Simulator (or pressing Command-Q).
Review the Source Code
The Single View Application template comes with a few source code files that set up the app environment. Most of the work is done by the
UIApplicationMain function, which is automatically called in your project’s
main.m source file. The
UIApplicationMain function creates an application object that sets up the infrastructure for your app to work with the iOS system. This includes creating a run loop that delivers input events to your app.
You won’t be dealing with the
main.m source file directly, but it’s interesting to understand how it works.
To look at the main.m source file
Make sure the project navigator is open in the navigator area.
The project navigator displays all the files in your project. If the project navigator isn’t open, click the leftmost button in the navigator selector bar. (Alternatively, display it by choosing View > Navigators > Show Project Navigator.)
Open the Supporting Files folder in the project navigator by clicking the disclosure triangle next to it.
Xcode opens the source file in the main editor area of the window.
Alternatively, double-click the
main.mfile to open it in a separate window.
The main.m File and the UIApplicationMain Function
main function in
main.m calls the
UIApplicationMain function within an autorelease pool.
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
@autoreleasepool statement supports memory management for your app. Automatic Reference Counting (ARC) makes memory management straightforward by getting the compiler to keep track of who owns an object;
@autoreleasepool is part of the memory management infrastructure.
The call to
UIApplicationMain creates two important initial components of your app:
An instance of the
UIApplicationclass, called the application object.
The application object manages the app event loop and coordinates other high-level app behaviors. The
UIApplicationclass, defined in the UIKit framework, doesn’t require you to write any additional code to get it to do its job.
An instance of the
AppDelegateclass, called the app delegate.
Xcode created this class for you as part of setting up the Single View Application template. The app delegate creates the window where your app’s content is drawn and provides a place to respond to state transitions within the app. The app delegate is where you write your custom app-level code. Like all classes, the
AppDelegateclass is defined in two source code files in your app: in the interface file,
AppDelegate.h, and in the implementation file,
As your app starts up, the application object calls predefined methods on the app delegate to give your custom code a chance to do its job—that’s when the interesting behavior for an app is executed.
The App Delegate Source Files
To understand the role of the app delegate in more depth, view your app delegate source files,
AppDelegate.h (the interface file) and
AppDelegate.m (the implementation file). To view the app delegate interface file, select
AppDelegate.h in the project navigator. The app delegate interface contains a single property:
window. With this property the app delegate keeps track of the window in which all of your app content is drawn.
Next, view the app delegate implementation file by selecting
AppDelegate.m in the project navigator. The app delegate implementation contains “skeletons” of important methods. These predefined methods allow the application object to talk to the app delegate. During a significant runtime event—for example, app launch, low-memory warnings, and app termination—the application object calls the corresponding method in the app delegate, giving it an opportunity to respond appropriately. You don’t need to do anything special to make sure these methods get called at the correct time—the application object handles that part of the job for you.
Each of these automatically implemented methods has a default behavior. If you leave the skeleton implementation empty or delete it from your
AppDelegate.m file, you get the default behavior whenever that method is called. Use these skeletons to put additional custom code that you want to be executed when the methods are called. In this tutorial, you won’t be using any custom app delegate code, so you don’t have to make any changes to the
Open Your Storyboard
You’re ready to start working on a storyboard for your app. A storyboard is a visual representation of the app’s user interface, showing screens of content and the transitions between them. You use storyboards to lay out the flow—or story—that drives your app.
To open your storyboard
In the project navigator, select
Xcode opens the storyboard in Interface Builder—its visual interface editor—in the editor area. The background of the storyboard is the canvas. You use the canvas to add and arrange user interface elements.
Your storyboard should look similar to this:
At this point, the storyboard in your app contains one scene, which represents a screen of content in your app. The arrow that points to the left side of the scene on the canvas is the storyboard entry point, which means that this scene is loaded first when the app starts. Right now, the scene that you see on the canvas contains a single view that’s managed by a view controller. You’ll learn more about the roles of views and view controllers after this tutorial.
When you ran your app in the iPhone 6 iOS Simulator, the view in this scene is what you saw on the device screen. But when you look at the scene on the canvas, you’ll notice that it doesn’t have the exact dimensions of the iPhone 6 screen. This is because the scene on the canvas is a generalized representation of your interface that can apply to any device in any orientation. You use this representation to create an adaptive interface, which is an interface that automatically adjusts so that it looks good in the context of the current device and orientation. You’ll learn how to make your interface adaptive in a little while.
Build the Basic Interface
It’s time to build the basic interface for the scene that lets you add a new item to the to-do list.
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, such as view controllers and gesture recognizers, define the behavior of your app but don’t appear onscreen.
To be able to add an item to the to-do list, you need a text field, the interface element that lets a user input a single line of text.
To add a text field to your scene
Open the Object library.
The Object library appears at the bottom of the utility area. If you don’t see the Object library, click its button, which is the third button from the left in the library selector bar. (Alternatively, display it by choosing View > Utilities > Show Object Library.)
A list appears showing each object’s name, description, and visual representation.
In the Object library, type
text fieldin the filter field to find the Text Field object quickly.
Drag a Text Field object from the Object library to your scene.
If you need to, you can zoom in using Editor > Canvas > Zoom.
Drag the text field so that it’s centered vertically and aligned with the left margin in the scene.
Stop dragging the text field when you see something like this:
The blue layout guides help you place the text field. Layout guides are visible only when you drag or resize objects next to them; they disappear when you let go of the text field.
If necessary, click the text field to reveal the resize handles.
You resize a UI element by dragging its resize handles, which are small white squares that appear on the element’s borders. You reveal an element’s resize handles by selecting it. In this case, the text field should already be selected because you just stopped dragging it. If your text field looks like the one below, you’re ready to resize it; if it doesn’t, select it on the canvas.
Resize the left and right edges of the text field until you see three vertical layout guides appear.
Stop resizing the text field when you see something like this:
Although you have the text field in your scene, there’s no instruction to the user about what to enter in the field. Use the text field’s placeholder text to prompt the user to enter the name of a new to-do item.
To configure the text field’s placeholder text
With the text field selected, open the Attributes inspector in the utility area.
The Attributes inspector appears when you select the fourth button from the left in the inspector selector bar. It lets you edit the properties of an object in your storyboard.
In the Attributes inspector, find the field labeled Placeholder and type
New to-do item.
Press Return to display the new placeholder text in the text field.
Preview Your Interface
Preview your app periodically to check that everything is looking the way you expect. You can preview your app interface using the assistant editor, which displays a secondary editor side-by-side with your main one.
To preview your interface
Click the Assistant button in the Xcode toolbar to open the assistant editor.
In the editor selector bar, switch the assistant editor from Automatic to Preview.
If you want more space to work, collapse the project navigator and utility area by clicking the Navigator and Utilities buttons in the Xcode toolbar.
Your Xcode window should look something like this:
As you see, the text field doesn’t look quite right. It extends past the edge of the screen. The interface you specified in your storyboard looks correct, so why is this happening in the iPhone preview?
As you learned earlier, you’re actually building an adaptive interface that scales for different sizes of iPhone and iPad. The scene you see by default in your storyboard shows a generalized version of your interface. Here, you’ll need to specify how the interface should adjust for specific devices. For example, when the interface shrinks down to an iPhone size, the text field should shrink. When the interface grows to an iPad size, the text field should grow. You can specify these kinds of interface rules easily using Auto Layout.
Adopt Auto Layout
Auto Layout is a powerful layout engine that helps you design adaptive layouts with ease. You describe your intent for the positioning of elements in a scene and then let the layout engine determine how best to implement that intent. You describe your intent using constraints—rules that explain where one element should be located relative to another, what size it should be, or which of two elements should shrink first when something reduces the space available for each of them.
The text field in this interface should appear a fixed amount of space from the top of the device screen and stretch to the horizontal margins, regardless of device.
To position the text field using Auto Layout
In your storyboard, select the text field.
On the canvas, click the Auto Layout Align icon.
Select the checkboxes next to Horizontal Center in Container and Vertical Center in Container.
Click the Add 2 Constraints button.
On the canvas, click the Auto Layout Pin icon.
Above “Spacing to nearest neighbor,” select the two horizontal red constraints by clicking on them.
These constraints indicate spacing to the nearest leading and trailing neighbors. Because the “Constrain to margins” checkbox is selected, the text field in this case is constrained to the margins of the view.
Click the Add 2 Constraints button.
The app interface preview updates to reflect the new constraints:
If you don’t get the behavior you expect, use the Xcode Auto Layout debugging features to help you. With the text field selected, click the Resolve Auto Layout Issues icon and choose Reset to Suggested Constraints to have Xcode update your interface with a valid set of constraints. Or click the Resolve Auto Layout Issues icon and choose Clear Constraints to remove all constraints on the text field, and then try following the steps above again.
Checkpoint: Run your app in iOS Simulator to make sure that the scene you created looks the way you expect it to. You should be able to click inside the text field and enter text using the keyboard (if you’d like, toggle the software keyboard by pressing Command-K). If you rotate the device (Command-Left Arrow or Command-Right Arrow) or run the app on a different device, the text field grows or shrinks to the appropriate size depending on the device’s orientation and screen size. Note that on some devices, the text field might be obscured by the keyboard in landscape orientation.
Although this scene doesn’t do much yet, the basic user interface is there and functional. Considering layout from the start ensures that you have a solid foundation to build upon.
You’re now well on your way to creating a basic interface with storyboards. In the remaining tutorials, you’ll learn more about adding interaction to your interface and writing code to create custom behavior. The chapters between the tutorials guide you through the concepts that you’ll put into practice while working on your app.