As you’re probably well aware, it has become something of a tradition to call the first project in any book on programming, “Hello, World.” We considered breaking with this tradition, but were scared that the Tiki gods would inflict some painful retribution on us for such a gross breach of etiquette. So, let’s do it by the book, shall we?
In this chapter, we’re going to use Xcode to create a small iOS application that will display the text, “Hello, World!” We’ll look at what’s involved in creating an iOS application project in Xcode, work through the specifics of using Xcode’s Interface Builder to design our application’s user interface, and then run our application on the iOS simulator. After that, we’ll give our application an icon to make it feel more like a real iOS application.
We have a lot to do here, so let’s get going.
Setting Up Your Project in Xcode
By now, you should have Xcode and the iOS SDK installed on your machine. You should also download the book project archive from the Learn Cocoa web site (http://www.learncocoa.org/). While you’re at it, take a look at the book forums at http://forum.learncocoa.org/. The book forums are a great place to discuss iOS development, get your questions answered, and meet up with like-minded people.
Note Even though you have the complete set of project files at your disposal in this book’s project archive, you’ll get more out of the book if you create each project by hand, rather than simply running the version you downloaded. By doing that, you’ll gain familiarity and expertise working with the various application development tools.
There’s no substitute for actually creating applications; software development is not a spectator sport.
The project we’re going to build in this chapter is contained in the 02 Hello World folder of the project archive.
Before we can start, we need to launch Xcode. Xcode is the tool that we’ll use to do most of what we do in this book. After downloading it from the Mac App Store, you’ll find it installed in the /Applications folder, as with most Mac applications. You’ll be using Xcode a lot, so you might want to consider dragging it to your dock, so you’ll have ready access to it.
If this is your first time using Xcode, don’t worry; we’ll walk you through every step involved in creating a new project. If you’re already an old hand but haven’t worked with Xcode 5, you will find that quite a bit has changed (mostly for the better, we think).
When you first launch Xcode, you’ll be presented with a welcome window like the one shown in Figure 2-1. From here, you can choose to create a new project, connect to a version-control system to check out an existing project, or select from a list of recently opened projects. The welcome window gives you a nice starting point, covering some of the most common tasks you’re likely to want to do after launching Xcode. All of these actions can be accessed through the menu as well, so close the window, and we’ll proceed. If you would rather not see this window in the future, just uncheck the Show this window when Xcode launches checkbox at the bottom of the window before closing it.
Figure 2-1. The Xcode welcome window
Note If you have an iPhone, iPad, or iPod touch connected to your machine, you might see a message when you first launch Xcode that asks whether you want to use that device for development. For now, click the Ignore button. Alternatively, the Organizer window might appear. This window shows (among other things) the devices that have been synchronized with your computer. In that case, just close the Organizer window. If you choose to join the paid iOS Developer Program, you will gain access to a program portal that will tell you how to use your iOS device for development and testing.
Create a new project by selecting New Project . . . from the File menu (or by pressing N). A new project window will open, showing you the project template selection sheet (see Figure 2-2). From this sheet, you’ll choose a project template to use as a starting point for building your application. The pane on the left side of the sheet is divided into two main sections: iOS and Mac OS X. Since we’re building an iOS application, select Application in the iOS section to reveal the iOS application templates.
Figure 2-2. The project template selection sheet lets you select from various templates when creating a new project
Each of the icons shown in the upper-right pane in Figure 2-2 represents a separate project template that can be used as a starting point for your iOS applications. The icon labeled Single View Application is the simplest template and the one we’ll be using for the first several chapters. The other templates provide additional code and/or resources needed to create common iPhone and iPad application interfaces, as you’ll see in later chapters.
Click the Single View Application icon (see Figure 2-2), and then click the Next button. You’ll see the project options sheet, which should look like Figure 2-3. On this sheet, you need to specify the Product Name and Company Identifier for your project. Xcode will combine these to generate a unique Bundle Identifierfor your app. You’ll also see a field that lets you enter an Organization Name, which Xcode will use to automatically insert a copyright notice into every source code file you create. Name your product Hello World, call your organization Apress, and then enter com.apress in the Company Identifierfield, as shown in Figure 2-3. Later, after you’ve signed up for the developer program and learned about provisioning profiles, you’ll want to use your own company identifier. We’ll talk more about the bundle identifier later in the chapter.
Figure 2-3. Selecting a product name and company identifier for your project. Use these settings for now
The next text box is labeled Class Prefix, and we should populate this with a sequence of at least three capital letters. These characters will be added to the beginning of the name of all classes that Xcode creates for us. This is done to avoid naming conflicts with Apple (which reserves the use of all two-letter prefixes) and other developers whose code we might use. In Objective-C, having more than one class with the same name will prevent your application from being built.
For the projects in the book, we’re going to use the prefix BID, which stands for Beginning iOS Development. While there are likely to be many classes named, for example, MyViewController, far fewer classes are likely to be named BIDMyViewController. This will significantly reduce the chance of conflicts.
We also need to specify the Devices. In other words, Xcode wants to know if we’re building an app for the iPhone and iPod touch, if we’re building an app for the iPad, or if we’re building a universal application that will run on all iOS devices. Select iPhone for the Devices if it’s not already selected. This tells Xcode that we’ll be targeting this particular app at the iPhone and iPod touch, which have roughly the same screen size and form factor. For the first part of the book, we’ll be using the iPhone device, but don’t worry—we’ll cover the iPad also.
Click Next again, and you’ll be asked where to save your new project using a standard save sheet (see Figure 2-4). If you haven’t already done so, jump over to the Finder, create a new master directory for these book projects, and then return to Xcode and navigate into that directory. Before you click the Create button, make note of the Source Control checkbox. We won’t be talking about git in this book, but Xcode includes some support for using git and other kinds of source control management (SCM) tools. If you are already familiar with git and want to use it, leave this checkbox enabled; otherwise, feel free to turn it off.
Figure 2-4. Saving your project in a project folder on your hard drive
Note Source Control Management (SCM) is a technique for keeping track of changes made to an application’s source code and resources while it’s being built. It also facilitates multiple developers working on the same application at the same time by providing tools to resolve conflicts when they arise. Xcode has built-in support for git, one of the most popular SCM systems in use today. We won’t be dealing with source control issues in this book, so it’s up to you to enable it or disable it, whichever works for you.
After choosing whether to create a git repository, create the new project by clicking the Create button.
After you dismiss the save sheet, Xcode will create and then open your project. You will see a new project windowx (see Figure 2-5). There’s a lot of information crammed into this window, and it’s where you will be spending a lot of your iOS development time.
Figure 2-5. The Hello World project in Xcode
Even if you are an old hand with earlier versions of Xcode, you’ll still benefit from reading through this section since it covers a lot of the new functionality in Xcode 5 (and a whole lot has changed since Xcode 3.x and Xcode 4). Let’s take a quick tour.
The Toolbar
The top of the Xcode project window is called the toolbar(see Figure 2-6). On the left side of the toolbar are controls to start and stop running your project, as well as a pop-up menu to select the scheme you want to run. A scheme brings together target and build settings, and the toolbar pop-up menu lets you select a specific setup with just one click.
Figure 2-6. The Xcode toolbar
The big box in the middle of the toolbar is the activity view. As its name implies, the activity view displays any actions or processes that are currently happening. For example, when you run your project, the activity view gives you a running commentary on the various steps it’s taking to build your application. If you encounter any errors or warnings, that information is displayed here, as well. If you click the warning or error, you’ll go directly to the issues navigator, which provides more information about the warning or error, as described in the next section.
On the right side of the toolbar are two sets of buttons. The left set lets you switch between three different editor configurations:
To the right of the editor buttons is set of toggle buttons that show and hide large panes on the left and right sides of the editor view, as well as the debug area at the bottom of the window. Click each of those buttons a few times to see these panes in action. You’ll learn more about how these are used soon.
The Navigator
Just below the toolbar, on the left side of the project window, is the navigator. If you used the navigator toggle button to hide this earlier, tap the button again to show the navigator. The navigator offers eight views that show you different aspects your project. Click one of the icons at the top of the navigator to switch among the following navigators, going from left to right:
Figure 2-7. The Xcode project navigator. Click one of the seven icons at the top of the view to switch navigators
Figure 2-8. The Xcode symbol navigator. Open the disclosure triangle to explore the classes, methods, and other symbols defined within each group
Figure 2-9. The Xcode find navigator. Be sure to check out the pop-up menus hidden under the word Find and under the buttons that are below the search field
Figure 2-10. The Xcode issue navigator. This is where you’ll find your compiler errors and warnings
Figure 2-11. The Xcode test navigator. The output of your unit tests will appear here
Figure 2-12. The Xcode debug navigator. Be sure to try out the detail slider at the bottom of the window, which allows you to specify the level of debug detail you want to see
The debug navigator lists the stack frame for each active thread. A stack frame is a list of the functions or methods that have been called previously, in the order they were called. Click a method, and the associated code appears in the editor pane. In the editor, there will be a second pane that lets you control the debugging process, display and modify data values, and access the low-level debugger. A slider at the bottom of the debug navigator allows you to control the level of detail it tracks. Slide to the extreme right to see everything, including all the system calls. Slide to the extreme left to see only your calls. The default setting of right in the middle is a good place to start.
Figure 2-13. The Xcode breakpoint navigator. The list of breakpoints is organized by file
Figure 2-14. The Xcode log navigator. The log navigator displays a list of builds, with the details associated with a selected view displayed in the edit pane
The Jump Bar
Across the top of the editor, you’ll find a special control called the jump bar. With a single click, the jump bar allows you to jump to a specific element in the hierarchy you are currently navigating. For example, Figure 2-15 shows a source file being edited in the edit pane. The jump bar is just above the source code. Here’s how it breaks down:
Figure 2-15. The Xcode editor pane showing the jump bar, with a source code file selected. The submenu shows the list of methods in the selected file
The jump bar is incredibly powerful. Look for it as you make your way through the various interface elements that make up Xcode 5.
Tip Like most of Apple’s OS X application, Xcode 5 includes full support for full-screen mode. Just click the full-screen button in the upper right of the project window to try out distraction-free, full-screen coding!
XCODE KEYBOARD SHORTCUTS
If you prefer navigating with keyboard shortcuts instead of mousing to on-screen controls, you’ll like what Xcode has to offer. Most actions that you will do regularly in Xcode have keyboard shortcuts assigned to them, such as B to build your application or N to create a new file.
You can change all of Xcode’s keyboard shortcuts, as well as assign shortcuts to commands that don’t already have one using Xcode’s preferences, under the Key Bindings tab.
A really handy keyboard shortcut is O, which is Xcode’s Open Quickly feature. After pressing it, start typing the name of a file, setting, or symbol, and Xcode will present you with a list of options. When you narrow down the list to the file you want, hitting the Return key will open it in the editing pane, allowing you to switch files in just a few keystrokes.
The Utility Area
As we mentioned earlier, the second-to-last button on the right side of the Xcode toolbar opens and closes the utility area. The upper part of the utility area is a context-sensitive inspector panel, with contents that change depending on what is being displayed in the editor pane. The lower part of the utility area contains a few different kinds of resources that you can drag into your project. You’ll see examples throughout the book.
Interface Builder
Earlier versions of Xcode included an interface design application called Interface Builder, which allowed you to build and customize your project’s user interface. One of the major changes introduced in later versions of Xcode is the integration of Interface Builder into the workspace itself. Interface Builder is no longer a separate stand-alone application, which means you don’t need to jump back and forth between Xcode and Interface Builder as your code and interface evolve. It’s been a few years since this shift occurred, but those of us who remember the days of a separate Interface Builder application are now pretty happy with how the direct integration of Interface Builder in Xcode worked out.
We’ll be working extensively with Xcode’s interface-building functionality throughout the book, digging into all its nooks and crannies. In fact, we’ll do our first bit of interface building a bit later in this chapter.
New Compiler and Debugger
One of the most important changes brought in by Xcode 4 lies under the hood: a brand new compiler and low-level debugger. Both are significantly faster and smarter than their predecessors.
For many years, Apple used GCC (the GNU C Compiler) as the basis for its compiler technology. But over the course of the past few years, it has shifted over completely to the LLVM (Low Level Virtual Machine) compiler. LLVM generates code that is faster by far than that generated by the traditional GCC. In addition to creating faster code, LLVM also knows more about your code, so it can generate smarter, more precise error messages and warnings.
Xcode is also tightly integrated with LLVM, which gives it some new superpowers. Xcode can offer more precise code completion, and it can make educated guesses as to the actual intent of a piece of code when it produces a warning, offering a pop-up menu of likely fixes. This makes errors like misspelled symbol names, mismatched parentheses, and missing semicolons a breeze to find and fix.
LLVM brings to the table a sophisticated static analyzer that can scan your code for a wide variety of potential problems, including problems with Objective-C memory management. In fact, LLVM is so smart about this that it can handle most memory management tasks for you, as long as you abide by a few simple rules when writing your code. We’ll begin looking at the wonderful new ARC feature called Automatic Reference Counting (ARC) in the next chapter.
A Closer Look at Our Project
Now that we’ve explored the Xcode project window, let’s take a look at the files that make up our new Hello World project. Switch to the project navigator by clicking the leftmost of the eight navigator icons on the left side of your workspace (as discussed in the “The Navigator View” section earlier in the chapter) or by pressing 1.
Tip The eight navigator configurations can be accessed using the keyboard shortcuts 1 to 8. The numbers correspond to the icons starting on the left, so 1 is the project navigator, 2 is the symbol navigator, and so on up to 8, which takes you to the log navigator.
The first item in the project navigator list bears the same name as your project—in this case, Hello World. This item represents your entire project, and it’s also where project-specific configuration can be done. If you single-click it, you’ll be able to edit a number of project configuration settings in Xcode’s editor. You don’t need to worry about those project-specific settings now, however. At the moment, the defaults will work fine.
Flip back to Figure 2-7. Notice that the disclosure triangle to the left of Hello World is open, showing a number of subfolders (which are called groups in Xcode):
Note The “folders” in the navigator area do not necessarily correspond to folders in your Mac’s file system. These are logical groupings within Xcode to help you keep everything organized and to make it faster and easier to find what you’re looking for while working on your application. Often, the items contained in those two project folders are stored directly in the project’s directory, but you can store them anywhere—even outside your project folder if you want. The hierarchy inside Xcode is completely independent of the file system hierarchy, so moving a file out of the Classes folder in Xcode, for example, will not change the file’s location on your hard drive.
It is possible to configure a group to use a specific file system directory using the utility pane. However, by default, new groups added to your project are completely independent of the file system, and their contents can be contained anywhere.
Introducing Xcode’s Interface Builder
In your project window’s project navigator, expand the Hello World group, if it’s not already open, and then select the file Main.storyboard. As soon as you do, the file will open in the editor pane, as shown in Figure 2-16. You should see something resembling an all-white iPhone screen centered on a plain white background, which makes a nice backdrop for editing interfaces. This is Xcode’s Interface Builder (sometimes referred to as IB), which is where you’ll design your application’s user interface.
Figure 2-16. We selected Main.storyboard in the project navigator. This opened the file in Interface Builder. It looks like this
Interface Builder has a long history. It has been around since 1988 and has been used to develop applications for NeXTSTEP, OpenStep, Mac OS X, and now iOS devices such as iPhone and iPad. As we noted earlier, Interface Builder used to be a separate application that was installed along with Xcode and worked in tandem with it. Now, Interface Builder is fully integrated into Xcode.
File Formats
Interface Builder supports a few different file types. The oldest is a binary format that uses the extension .nib, whose newer cousin is an XML-based format that uses the extension .xib. Both of these formats contain exactly the same sort of document, but the .xib version, being a text-based format, has many advantages, especially when you’re using any sort of SCM.
Note The iOS project templates all use .xib files by default; but for the first 20 years Interface Builder existed, all its files had the extension, .nib. As a result, most developers took to calling Interface Builder files nib files. Interface Builder files are often called nib files, regardless of whether the extension actually used for the file is .xib or .nib. In fact, Apple still uses the terms nib and nib file throughout its documentation.
Each nib file can contain any number of objects; but when working on iOS projects, each nib file will usually contain a single view (often a full-screen view) and controllers or other objects that it is connected to. This lets us compartmentalize our applications, only loading the nib file for a view when it’s needed for display. The end result: We save memory when our app is running on a memory-constrained iOS device.
The other file format that IB has supported for the past few years is the storyboard. You can think of a storyboard as a “meta-nib file” since it can contain several views and controllers, as well as information about how they are connected to each other when the application runs. Unlike a nib file, the contents of which are loaded all at once, a storyboard never loads all its contents at once. Instead, you ask it to load particular views and controllers when you need them.
We’ll be dealing with both storyboards and nibs throughout the book. In the current example we’re working on, Xcode has created a storyboard for us, so that’s what we’ll be looking at first.
You’re now looking at the primary tool you’ll use for building user interfaces for iOS apps. Now, let’s say that you want to create an instance of a button. You could create that button by writing code, but creating an interface object by dragging a button out of a library and specifying its attributes is so much simpler, and it results in exactly the same thing happening at runtime.
The Main.storyboard file we are looking at right now is loaded automatically when your application launches—for the moment, don’t worry about how—so it is the right place to add the objects that make up your application’s user interface. When you create objects in Interface Builder, they’ll be instantiated in your program when that storyboard or nib file is loaded. You’ll see many examples of this process throughout this book.
The Storyboard
Every storyboard is compartmentalized into one or more pairs of views and controllers. The view is the part you can see graphically and edit in Interface Builder, while the controller is application code you will write to make things happen when a user interacts with your app. The controllers are where the real action of your application happens.
In IB, you often see a view represented by an iPhone-sized rectangle (though other sizes are possible), and our current example is no exception. Click anywhere in this rectangle, and you’ll see a row of three icons shown below it. Drag your mouse over each of them, and you’ll see tooltips pop up with their names: View Controller, First Responder, and Exit. Forget about Exit for now, and focus instead on the two that are really important.
We’ll talk more about these objects starting in the next chapter, so don’t worry if you’re a bit fuzzy right now on when you would use First Responder or how a View Controller gets loaded.
Apart from those icons, the rest of what you see in the editing area is the space where you can place graphical objects. But before we get to that, there’s one more thing you should see about IB’s editor area: its hierarchy view. Click the little button in the lower-left corner of the editing area, and you’ll see the hierarchy view slide in from the left. This shows all the contents of the storyboard, split up into scenes containing chunks of related content. In our case, we have just one scene, called View Controller Scene. You’ll see that it contains an item called View Controller, which in turn contains an item called View (along with some other things you’ll learn about later). This is a pretty handy way of getting an overview of your content. Everything you see in the main editing area is mirrored here.
The View icon represents an instance of the UIView class. A UIView object is an area that a user can see and interact with. In this application, we will have only one view, so this icon represents everything that the user can see in our application. Later, we’ll build more complex applications that have more than one view. For now, just think of this as what the user can see when using your application.
Note Technically speaking, our application will actually have more than one view. All user interface elements that can be displayed on the screen—including buttons, text fields, and labels—are descendants of UIView. When you see the term view used in this book, however, we will generally be referring only to actual instances of UIView, and this application has only one of those.
If you click the View icon, Xcode will automatically highlight the iPhone-sized screen rectangle that we were talking about earlier. This is where you can design your user interface graphically.
The Library
The utility view, which makes up the right side of the workspace, is divided into two sections (see Figure 2-17). If you’re not currently seeing the utility view, click the rightmost of the three View buttons in the toolbar, select View Utilities Show Utilities, or press 0 (Option-Command-Zero).
Figure 2-17. The library is where you’ll find stock objects from the UIKit that are available for use in Interface Builder. Everything above the library but below the toolbar is known collectively as the inspector
The bottom half of the utility view is called the library pane, or just plain library. The library is a collection of reusable items you can use in your own programs. The four icons in the bar at the top of the library pane divide the library into four sections:
Note The items in the object library are primarily from the iOS UIKit, which is a framework of objects used to create an app’s user interface. UIKit fulfills the same role in Cocoa Touch as AppKit does in Cocoa. The two frameworks are similar conceptually; however, because of differences in the platforms, there are obviously many differences between them. On the other hand, the Foundation framework classes, such as NSString and NSArray, are shared between Cocoa and Cocoa Touch.
Note the search field at the bottom of the library. Do you want to find a button? Type button in the search field, and the current library will show only items with “button” in the name. Don’t forget to clear the search field when you are finished searching.
Adding a Label to the View
Let’s give Interface Builder a try. Click the Object Library icon (it looks like a cube) at the top of the library to bring up the object library. Just for fun, scroll through the library to find a Table View. That’s it—keep scrolling, and you’ll find it. Or wait! There’s a better way: just type the words Table View in the search field. Isn’t that so much easier?
Tip Here’s a nifty shortcut: press ^3 to jump to the search field and highlight its contents. Next, you can just type what you want to search for.
Now find a Label in the library. It is likely on or near the top of the list. Next, drag the label onto the view we saw earlier. (If you don’t see the view in your editor pane, click the View icon in the Interface Builder dock.) As your cursor appears over the view, it will turn into the standard, “I’m making a copy of something” green plus sign you know from the Finder. Drag the label to the center of the view. A pair of blue guidelines—one vertical and one horizontal—will appear when your label is centered. It’s not vital that the label be centered, but it’s good to know those guidelines are there. Figure 2-18 shows what our workspace looked like just before we released our drag.
Figure 2-18. We’ve found a label in our library and dragged it onto our view. Note that we typed Label into the library search field to limit our object list to those containing the word Label
User interface items are stored in a hierarchy. Most views can contain subviews; however, there are some, like buttons and most other controls, that can’t. Interface Builder is smart. If an object does not accept subviews, you will not be able to drag other objects onto it.
By dragging a label directly to the view we’re editing, we add it as a subview of that main view (the view named View), which will cause it to show up automatically when that view is displayed to the user. Dragging a Label from the library to the view called View adds an instance of UILabel as a subview of our application’s main view.
Let’s edit the label so it says something profound. Double-click the label you just created, and type the text, Hello, World! Next, click off the label, and then reselect it and drag the label to recenter it or position it wherever you want it to appear on the screen.
Guess what? Once we save, we’re finished. Select File Save, or press S. Now check out the pop-up menu at the upper left of the Xcode project window. This is actually a multi-segment pop-up control. The left side lets you choose a different compilation target and do a few other things, but we’re interested in the right side, which lets you pick which device you want to run on. Click the right side and you’ll see a list of available devices. At the top, if you have any iOS device plugged in and ready to go, you’ll see it listed. Otherwise, you’ll just see a generic iOS Device entry. Below that, you’ll see a whole section, headed by iOS Simulator, listing all the kinds of devices that can be used with the iOS Simulator. From that lower section, choose iPhone Retina (4-inch), so that our app will run in the simulator, configured as if it were an iPhone 5. If you are a member of Apple’s paid iOS Developer Program, you can try running your app on your phone. In this book, we’ll stick with the simulator as much as possible, since running in the simulator doesn’t require any paid membership.
Ready to run? Select Product Run or press R. Xcode will compile your app and launch it in the iOS simulator (see Figure 2-19).
Figure 2-19. Here’s the Hello, World program in its full iPhone glory!
Note If your iOS device is connected to your Mac when you build and run, things might not go quite as planned. In a nutshell, in order to be able to build and run your applications on your iPhone, iPad, or iPod touch, you must sign up and pay for one of Apple’s iOS Developer Programs, and then go through the process of configuring Xcode appropriately. When you join the program, Apple will send you the information you’ll need to get this done. In the meantime, most of the programs in this book will run just fine using the iPhone or iPad simulator.
When you are finished admiring your handiwork, you can head back over to Xcode. Xcode and the simulator are separate applications.
Tip You are welcome to quit the simulator once you finish examining your app, but you’ll just be restarting it in a moment. If you leave the simulator running and ask Xcode to run your application again, Xcode will ask you to confirm that you want to stop your existing app before starting a new instance of it. If this seems confusing, feel free to quit the simulator each time you finish testing your app. No one will know!
Wait a second! That’s it? But we didn’t write any code. That’s right.
Pretty neat, huh?
Well, how about if we wanted to change some of the properties of the label, like the text size or color? We would need to write code to do that, right? Nope. Let’s see just how easy it is to make changes.
Changing Attributes
Head back to Xcode and single-click the Hello, World label to select it. Now turn your attention to the area above the library pane. This part of the utility pane is called the inspector. Like the library, the inspector pane is topped by a series of icons, each of which changes the inspector to view a specific type of data. To change the attributes of the label, we’ll need the fourth icon from the left, which brings up the object attributes inspector (see Figure 2-20).
Figure 2-20. The object attributes inspector showing our label’s attributes
TIP The inspector, like the project navigator, has keyboard shortcuts corresponding to each of its icons. The inspector’s keyboard shortcuts start with 1 for the leftmost icon, 2 for the next icon, and so on. Unlike the project navigator, the number of icons in the inspector is context-sensitive and changes depending on which object is selected in the navigator and/or editor.
Go ahead and change the label’s appearance to your heart’s delight. Feel free to play around with the font, size, and color of the text. Note that if you increase the font size, you may need to resize the label itself to make room for larger text. Once you’re finished playing, save the file and select Run again. The changes you made should show up in your application, once again without writing any code.
Note Don’t worry too much about what all of the fields in the object attributes inspector mean, or fret if you can’t get one of your changes to show up. As you make your way through the book, you’ll learn a lot about the object attributes inspector and what each of the fields does.
By letting you design your interface graphically, Interface Builder frees you to spend time writing the code that is specific to your application, instead of writing tedious code to construct your user interface.
Most modern application development environments have some tool that lets you build your user interface graphically. One distinction between Interface Builder and many of these other tools is that Interface Builder does not generate any code that must be maintained. Instead, Interface Builder creates Objective-C objects, just as you would in your own code, and then serializes those objects into the storyboard or nib file so that they can be loaded directly into memory at runtime. This avoids many of the problems associated with code generation and is, overall, a more powerful approach.
Some iPhone Polish—Finishing Touches
Now let’s put a last bit of spit and polish on our application to make it feel a little more like an authentic iPhone application. First, run your project. When the simulator window appears, click the iPhone’s home button (the black button with the white square at the very bottom of the window). That will bring you back to the iPhone home screen (see Figure 2-21). Notice anything a bit, well, boring?
Figure 2-21. The AppIcon boxes on your project’s assets catalog. This is where you can set your application’s icon
Take a look at the Hello, World icon at the top of the screen. Yeah, that icon will never do, will it? To fix it, you need to create an icon and save it as a portable network graphic (.png) file. Actually, for best results you should create three icons. One needs to be 120 × 120 pixels in size, another 80 × 80, and yet another needs to be 58 × 58 pixels. Why three icons? The first one is the icon that will be used for displaying your app on the iPhone home screen. The second one will be shown if your app shows up in the results list from a Spotlight search on the phone. The third icon will be displayed in the Settings app. If you don’t supply either of the smaller ones, the larger one will be scaled down appropriately; but for best results, you (or a graphic artist on your team) should probably scale it in advance.
Note The issue of icon sizes is even more complex than this. Before iOS 7, the side dimension of an icon for all modern iPhones was 114 × 114 pixels. But if you still wanted to support older, non-Retina iPhones, you needed to include an icon at half that resolution too, 57 × 57. Then there’s the issue of the iPad, which has still other icons sizes, both Retina and non-Retina, for both iOS 7 and for earlier versions of iOS! For now, we’ll avoid diving further down this particular rabbit hole, and just provide icons for an iPhone running iOS 7.
Do not try to match the style of the buttons that are already on the phone when you create the icons; your iPhone will automatically round the edges. Just create normal, square images. We have provided a set of icon images in the project archive 02 - Hello World - icons folder. These images are called icon-120.png, icon-80, and icon-58.png; feel free to use them if you don’t want to create your own.
Note For your application’s icon, you must use .png images; in fact, you should actually use that format for all images in your iOS projects. Xcode automatically optimizes .png images at build time, which makes them the fastest and most efficient image type for use in iOS apps. Even though most common image formats will display correctly, you should use .png files unless you have a compelling reason to use another format.
After you’ve designed your app icon, press 1 to open the project navigator, and look inside the Hello World group for an item called Images.xcassets. This is something called an asset catalog, and it is new to Xcode 5. By default, each new Xcode project is created with an asset catalog, ready to hold your app icon and other images. Select Images.xcassets and turn your attention to the editing pane.
On the left side of the editing pane, you’ll see a white column with list entries labeled AppIcon and LaunchImage. Make sure that the AppIcon item is selected. To the right of that column, you’ll see a white space with the text “AppIcon” in the upper-left corner, as well as dashed-line squares corresponding to the three icons we just talked about (see Figure 2-21). This is where we’ll drag our app icons.
You’ll see that beneath each icon is a bit of text explaining where that version of the icon will be used. It also tells you what size the icon should be. But here’s the tricky part: Xcode shows you the size in points, not pixels. In this context, a point is a particular size on a screen. It’s the size of a single pixel on the earliest iPhones (everything earlier than the iPhone 4), as well as on the iPad 1, iPad 2, and iPad Mini. On other devices, those with a Retina display, a single point is actually a 2 × 2 pixel square. The items shown in the asset catalog hint at this with their 2x labels, but those are really just labels. To figure out what size an item really expects, select one of them and press 4 to open the attributes inspector on the right side of the window. This will show you both the size (again in points) and the scale, which for each of these icons is 2x. Multiply the size by the scale, and you’ll get the actual pixel size that’s required. Check each of the items in the AppIcon box, and the inspector will give you the details. They should match up with what we described earlier, but you never know what Apple has up its sleeve. Between the time this book goes to print and the time you read this, Apple may have some fantastic new devices that require still more icons!
From the Finder, drag icon-120.png to the item labeled “iPhone App”— this should be the one on the right. This will copy icon-120.png into your project and set it as your application’s icon. Next, drag icon-80.png from the Finder to the middle square, which will set that as your application’s Spotlight icon. Finally, drag icon-58.png to the left square, setting the icon to be used for Settings in iOS 7.
Now compile and run your app. When the simulator has finished launching, press the button with the white square to go home, and check out your snazzy new icon. Ours is shown in Figure 2-22. To see one of the smaller icons in use, swipe down inside the home screen to bring up the spotlight search field, and start typing the word, Hello—you’ll see your new app’s icon appear immediately.
Figure 2-22. Your application now has a snazzy icon!
Note If you want to clear out old applications from the iOS simulator’s home screen, you can choose iOS Simulator Reset Content and Settings. . . from the iOS simulator’s application menu.
Bring It on Home
Pat yourself on the back. Although it may not seem like you accomplished all that much in this chapter, we actually covered a lot of ground. You learned about the iOS project templates, created an application, learned a ton about Xcode 5, started using Interface Builder, and learned how to set your application icon.
The Hello, World program, however, is a strictly one-way application. We show some information to the users, but we never get any input from them. When you’re ready to see how to go about getting input from the user of an iOS device and taking actions based on that input, take a deep breath and turn the page.
3.12.108.18