Beginning iPhone Development with Swift: Exploring the iOS SDK (2014)
Chapter 2. Appeasing the Tiki Gods
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’s source code archive from the Apress web site (http://apress.com). 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 source code 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 source code 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 6, 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 check box 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. 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. Some of the examples in later chapters require the use of a real device because they use features that are not available on the iOS simulator. You’ll need to join the iOS Developer Program to try out those examples.
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 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 identifier for 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 Identifier field, 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.
Figure 2-3. Selecting a product name and company identifier for your project. Use these settings for now
The Language field lets you select the programming language that you want to use. You can choose between Objective-C and Swift. Since you’re reading the Swift version of this book, the appropriate choice here is, of course, Swift.
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 few chapters of the book, we’ll be using the iPhone device, but don’t worry—we’ll cover the iPad also.
Leave the Core Data check box unchecked—we’ll make use of it in Chapter 13. 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, take note of the Source Control check box. 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, enable this check box; 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.
The Xcode Project Window
After you dismiss the save sheet, Xcode will create and then open your project. You will see a new project window (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 may still benefit from reading through this section, since Apple has a habit of rearranging things and making improvements from release to release. Let’s take a quick tour.
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 menus lets you select a specific setup quickly and easily.
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 Issue 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:
· The Editor Area gives you a single pane dedicated to editing a file or project-specific configuration values.
· The incredibly powerful Assistant Editor splits the Editor Area into two panes, left and right. The pane on the right is generally used to display a file that relates to the file on the left, or that you might need to refer to while editing the file on the left. You can manually specify what goes into each pane, or you can let Xcode decide what’s most appropriate for the task at hand. For example, if you’re designing your user interface on the left, Xcode will show you the code that the user interface is able to interact with on the right. You’ll see the Assistant Editor at work throughout the book.
· The Version Editor button converts the editor pane into a time machine–like comparison view that works with version control systems such as Subversion and Git. You can compare the current version of a source file with a previously committed version or compare any two earlier versions with each other.
To the right of the editor buttons is a 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.
Just below the toolbar, on the left side of the project window, is the Navigator. The Navigator offers eight views that show you different aspects of your project. Click each of the icons at the top of the navigator to switch among the following navigators, going from left to right:
· Project Navigator: This view contains a list of files in your project (see Figure 2-7). You can store references to everything you expect—from source code files to artwork, data models, property list (or .plist) files (discussed in the “A Closer Look at Our Project” section later in this chapter), and even other project files. By storing multiple projects in a single workspace, those projects can easily share resources. If you click any file in the navigator view, that file will display in the Editor Area. In addition to viewing the file, you can also edit it (if it’s a file that Xcode knows how to edit).
Figure 2-7. The Xcode Project Navigator. Click one of the eight icons at the top of the view to switch navigators
· Symbol Navigator: As its name implies, this navigator focuses on the symbols defined in the workspace (see Figure 2-8). Symbols are basically the items that the compiler recognizes, such as classes, enumerations, structs, and global variables.
Figure 2-8. The Xcode Symbol Navigator. Open the disclosure triangle to explore the classes, methods, and other symbols defined within each group
· Find Navigator: You’ll use this navigator to perform searches on all the files in your workspace (see Figure 2-9). At the top of this pane is a multileveled pop-up control that lets you select Replace instead of Find, along with other options for applying search criteria to the text you enter. Below the text field, other controls let you choose to search in the entire project or just a portion of it, and specify whether searching should be case-sensitive.
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
· Issue Navigator: When you build your project, any errors or warnings will appear in this navigator, and a message detailing the number of errors will appear in the activity view at the top of the window (see Figure 2-10). When you click an error in the issue navigator, you’ll jump to the appropriate line of code in the editor.
Figure 2-10. The Xcode Issue Navigator. This is where you’ll find your compiler errors and warnings
· Test Navigator: If you’re using Xcode’s integrated unit testing capabilities (a topic that we unfortunately can’t fit into this book), this is where you’ll see the results of your unit tests (see Figure 2-11).
Figure 2-11. The Xcode Test Navigator. The output of your unit tests will appear here
· Debug Navigator: This navigator is your main view into the debugging process (see Figure 2-12). If you are new to debugging, you might check out this part of the Xcode Overview(http://developer.apple.com/library/ios/documentation/ToolsLanguages/Conceptual/Xcode_Overview/DebugYourApp/DebugYourApp.html). The Debug Navigator lists the stack frame for each active thread. A stack frameis 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 button at the bottom of the debug navigator allows you to control which stack frames are visible and another lets you choose whether to show all threads or just the threads that have crashed or stopped on a breakpoint.
Figure 2-12. The Xcode Debug Navigator. Controls at the bottom of the navigator let you control the level of detail you want to see
· Breakpoint Navigator: The breakpoint navigator lets you see all the breakpoints that you’ve set (see Figure 2-13). Breakpoints are, as the name suggests, points in your code where the application will stop running (or break), so that you can look at the values in variables and do other tasks needed to debug your application. The list of breakpoints in this navigator is organized by file. Click a breakpoint in the list and that line will appear in the editor pane. Be sure to check out the plus sign (+) button at the lower-left corner of the project window when in the breakpoint navigator. This button opens a pop-up that lets you add four different types of breakpoints, including symbolic breakpoints, which are the ones that you will use most often.
Figure 2-13. The Xcode Breakpoint Navigator. The list of breakpoints is organized by file
· Report Navigator: This navigator keeps a history of your recent build results and run logs (see Figure 2-14). Click a specific log, and the build command and any build issues are displayed in the edit pane.
Figure 2-14. The Xcode Report Navigator. The Report Navigator displays a list of builds, with the details associated with a selected view displayed in the editor 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:
· The funky-looking icon at the left end of the jump bar is actually a pop-up menu that displays submenus listing recent files, counterparts, superclasses, and subclasses, siblings, categories, includes, and more! The submenus shown here will take you to just about any other code that touches the code currently open in the editor.
· To the right of the über menu are left and right arrows that take you back to the previous file and return you to the next file, respectively.
· The jump bar includes a segmented pop-up that displays the hierarchical path to reach the selected file in the project. You can click any segment showing the name of a group or a file to see all the other files and groups located at the same point in the hierarchy. The final segment shows a list of items within the selected file. In Figure 2-15, you’ll see that the tail end of the jump bar is a pop-up that shows the methods and other symbols contained within the currently selected file. The jump bar shows the file AppDelegate.swift, with a submenu listing the symbols defined in that file.
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.
Tip Like most of Apple’s OS X applications, Xcode 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.
Earlier versions of Xcode included a separate 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
Among the most important changes that were brought in by Xcode 4 lies under the hood: a brand-new compiler and a low-level debugger. Both are significantly faster and smarter than their predecessors and each release since then has added improvements.
For many years, Apple used GCC (the GNU Compiler Collection) 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 and mismatched parentheses 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 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” 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 Report 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):
· Hello World: The first folder, which is always named after your project, is where you will spend the bulk of your time. This is where most of the code that you write will go, as will the files that make up your application’s user interface. You are free to create subfolders under the Hello World folder to help organize your code, and you’re even allowed to use other groups if you prefer a different organizational approach. While we won’t touch most of the files in this folder until the next chapter, there is one file we will explore when we use Interface Builder in the next section:
o Main.storyboard contains the user interface elements specific to your project’s main view controller.
· Supporting Files: This folder, located inside the Hello World folder, contains files and resources that aren’t Swift classes, but that are necessary to your project. Typically, you won’t spend a lot of time in the Supporting Files folder. When you create a new iOS application project, this folder contains just one file called Info.plist, which contains important information about the application, such as its name, whether it requires any specific features to be present on the devices on which it is run, and so on.
· Hello WorldTests: This folder contains the initial files you’ll need if you want to write some unit tests for your application code. We’re not going to talk about unit testing in this book, but it’s nice that Xcode sets up some of these things for you in each new project you create. Like the Hello World folder, this one contains its own Supporting Files folder with an Info.plist file.
· Products: This folder contains the application that this project produces when it is built. If you expand Products, you’ll see an item called Hello World.app, which is the application that this particular project creates. It also contains an item called Hello WorldTests.xctest, which represents the testing code. Both of these items are called build targets. Because we have never built either of these, they’re both red, which is Xcode’s way of telling you that a file reference points to something that is not there.
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 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 Supporting Files 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 iOS device 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, OS X, and now iOS devices such as the iPhone and the 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.
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. For the first 20 years of Interface Builder’s life, 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 one 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. A newly-created iOS project contains a nib file called LaunchScreen.xib that contains a screen layout that will be shown, by default, when your application launches. We’ll talk more about this file at the end of the chapter.
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 view 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 cannot contain freestanding views and it never loads all its contents at once. Instead, you ask it to load particular controllers when you need them. The iOS project templates in Xcode 6 all use storyboards, so all of the examples in this book will start with a storyboard. Now let’s go back to Interface Builder and the Main.storyboard file for our Hello World application (Figure 2-16).
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.
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 a square and our current example is no exception. That square represents the screen of an iOS device (actually, it represents a view controller, a concept that you’ll be introduced to in the next chapter, but this particular view controller covers the whole screen of the device, so it’s pretty much the same thing). Why is the screen square? After all, this is an iPhone project and iPhones just don’t look like that! In the early days of iOS, there were just the iPhone and iPod touch. The first versions of Interface Builder that supported iOS development presented an iPhone-shaped design area where you now see a square. When the iPad came along, Interface Builder was enhanced to let you design both iPhone-shaped and iPad-shaped user interfaces. To build an application that worked on both types of device (a universal application), you had to construct one storyboard (or nib file) for the iPhone and another for the iPad. When working with your iPad storyboard, Interface Builder gave you an iPad-shaped outline to design with. In Xcode 6 and iOS 8, things have changed. Now, Apple wants to encourage you to build applications that work as well as possible on screens of any size. Instead of two storyboards, there should be only one. When your application launches onto a device, it is supposed to adapt itself to the shape of screen that it finds (in fact, Apple refers to applications designed in this way as adaptive applications). So now, Interface Builder presents you with a square design area to encourage you not to think in terms of the screen size of any particular device. In the course of the first half of this book, you’ll see how to design adaptive applications, but we need to walk before we can run, and our first few examples will be built for iPhone and iPod touch-sized screens.
Returning to our storyboard, click anywhere in the square outline, and you’ll see a row of three icons at the top of it, like those in Figure 2-16. Move 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.
· View Controller represents a controller object that is loaded from file storage along with its associated view. The task of the view controller is to manage what the user sees on the screen. A typical application has several view controllers, one for each of its screens. It is perfectly possible to write an application with just one screen, and hence one view controller, and many of the examples in this book have only one view controller.
· First Responder is, in very basic terms, the object with which the user is currently interacting. If, for example, the user is currently entering data into a text field, that field is the current first responder. The first responder changes as the user interacts with the user interface, and the First Responder icon gives you a convenient way to communicate with whatever control or other object is the current first responder, without needing to write code to determine which control or view that might be.
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—or the Document Outline to give it its correct name. The Document Outline is shown in Figure 2-17.
Figure 2-17. The Document Outline contains a useful hierarchical representation of everything in the storyboard
Click the little button in the lower-left corner of the editing area, and you’ll see the Document Outline 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 the View Controller Scene. You’ll see that it contains an item called View Controller, which in turn contains an item called the 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 currently 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 several views. For now, just think of this view as an object that the user can see when using your application.
If you click the View icon, Xcode will automatically highlight the square screen outline that we were talking about earlier. This is where you can design your user interface graphically.
The utility view, which makes up the right side of the workspace, is divided into two sections (see Figure 2-18). 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-18. 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 it into four sections:
· File Template Library: This section contains a collection of file templates you can use when you need to add a new file to your project. For example, if you want to add a new file to your project, one way to do it is to drag a file of the required type from the file template library.
· Code Snippet Library: This section features a collection of code snippets you can drag into your source code files. Have you written something you think you’ll want to use again later? Select it in your text editor and drag it to the code snippet library.
· Object Library: This section is filled with reusable objects, such as text fields, labels, sliders, buttons, and just about any object you would ever need to design your iOS interface. We’ll use the object library extensively in this book to build the interfaces for our sample programs.
· Media Library: As its name implies, this section is for all your media, including pictures, sounds, and movies.
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 circle with a square in the center—you can see it in Figure 2-18) 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. 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 Document Outline.) 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 that those guidelines are there.Figure 2-19 shows what our workspace looked like just before we released our drag.
Figure 2-19. 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 ofUILabel 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 multisegment 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 5s, so that our app will run in the simulator, configured as if it were an iPhone 5s. If you are a member of Apple’s paid iOS Developer Program, you can try running your app on your own device. 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-20).
Figure 2-20. Here’s the Hello World program in its full iPhone glory! But something is wrong…
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.
Well, that’s not quite right. The label was centered in Interface Builder, but on the simulator, it’s way off to the right. What went wrong? When you place a view, unless you tell it otherwise, Interface Builder assumes you are positioning it relative to the top-left corner of the view that you dropped it onto. The problem is that the view that we dropped the label onto is wider than the screen of the simulated iPhone that we ran the application on. When we centered the label in Interface Builder, we weren’t centering it on the screen we were going to use to test the application. This is a problem that you’ll face all the time—the screen of the device that your application ends up running on may not be the same size as the design surface that you used in Interface Builder. As we said earlier, this is deliberate—Apple wants you to design on an abstract square view as much as possible and have your screen layouts adapt to the screens that they meet at runtime.
So how do we fix this? Back in iOS 6, Apple added a technology called Auto Layout, which lets you add constraints to the views in your design that express how they should change position and/or size to adapt to the space that’s actually available on screen. You’ll see how to use Interface Builder to configure Auto Layout constraints starting in the next chapter, but for now, let’s take a simpler approach—we’ll change the square view that we’re using as the basis for our design into one that looks more like the iPhone simulator that we’re actually running the application on. To this, select Main.storyboard in the Project Navigator and then click the File Inspector icon in the Inspector selector pane at the top of the Utility area, as shown in Figure 2-21.
Figure 2-21. Reconfiguring the storyboard for an iPhone
Toward the bottom of the File Inspector pane, you’ll see two check boxes labeled Use Auto Layout and Use Size Classes, both of which are selected. Click the Use Size Classes check box to deselect it. When you do this, Xcode prompts you for confirmation and asks whether you want to keep size class data for the iPhone or the iPad. Select to keep the size class data for the iPhone and click Disable Size Classes. Immediately, the screen outline in the Editor area resizes itself to look like an iPhone (see Figure 2-22) and you can see clearly why your label did not appear in the correct location.
Figure 2-22. The storyboard editor with Size Classes disabled, configured for iPhone
Now drag the label back into the center and run the application again—this time, the label should be where you expected it to be (Figure 2-23).
Figure 2-23. The Hello World application working as planned
When you are finished admiring your handiwork, you can head back over to Xcode. Xcode and the simulator are separate applications. 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.
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. As you saw in Figure 2-21, 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 Attributes Inspector (see Figure 2-24).
Figure 2-24. 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 selectRun 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 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 Attributes Inspector and what most of the fields do.
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 Swift 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 again. When the simulator window appears, press H. That will bring you back to the iPhone home screen (see Figure 2-25). Notice anything a bit, well, boring?
Figure 2-25. The Hello World application on the home screen
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 five icons, with sizes 180 x 180 pixels, 120 x 120 pixels, 87 x 87 pixels, 80 x 80 pixels and 58 x 58 pixels. Why so many icons? The icons are used on the iPhone home screen, in the Settings app and in the results list for a Spotlight search. That accounts for three of them, but that’s not the end of the story—the iPhone 6 Plus, with its larger screen, requires higher resolution icons, adding another three to the list. Fortunately, one of these is the same size as an icon from the other set, so you actually only need to create five versions of your application icon. If you don’t supply some of the smaller ones, a 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 × 144 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 8 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 8.
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-180.png, icon-120.png, icon-87.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.
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. By default, each new Xcode project is created with an asset catalog, ready to hold your app icon and other images. SelectImages.xcassets and turn your attention to the editing pane.
On the left side of the editing pane, you’ll see a white column with an entry labeled AppIcon. 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 for the five icons we just talked about (see Figure 2-26). This is where we’ll drag our app icons.
Figure 2-26. The AppIcon boxes on your project’s assets catalog. This is where you can set your application’s icon
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 most of the later devices with a Retina display, a single point is actually a 2 × 2–pixel square. The exception is the iPhone 6 Plus, where a single point is a 3 × 3–pixel square. The items shown in the asset catalog hint at this with their 2x and 3x 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 either 2x or 3x. Multiply the size by the scale, and you’ll get the actual pixel size that’s required. Select each of the items in the AppIcon box in turn, 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 2x” and icon-180.png to “iPhone App 3x”—these should be the ones on the right. This will copy those icons into your project and set them as your application’s icon. Next, drag icon-80.png from the Finder to “iPhone Spotlight 2x” and icon-120.png (again) to “iPhone Spotlight 3x”, (the group in the middle, not the group on the left), which will set them as your application’s Spotlight icons. Finally, drag icon-58.png to “iPhone Settings 2x” and icon-87.png to “iPhone Settings 3x”, setting the icons to be used for Settings.
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-27. 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-27. Your application now has a snazzy icon!
Note As you work through this book, your simulator’s home screen will get cluttered with the icons for the example applications that we’ll be running. If you want to clear out old applications from the home screen, you can choose iOS Simulator Reset Content and Settings…from the iOS simulator’s application menu.
The Launch Screen
There’s just one more thing we need to talk about before moving on. When you launched your application, you probably noticed the mainly white launch screen that appeared while the application was being loaded. iOS applications have always had a launch screen. Since the process of loading an application into memory takes time (and the larger the application, the longer it takes), the purpose of this screen is to let the user see, as quickly as possible, that something is happening. Prior to iOS 8, you could supply an image (in fact, several images of different sizes) to act as your app’s launch screen. iOS would load the correct image and immediately display it before loading the rest of your application. With iOS 8, you still have that option, but Apple now recommends that you use a launch file instead of a launch image, or as well as a launch image if your application still needs to support earlier releases.
What’s a launch file? It’s a nib file or storyboard that contains the user interface for your launch screen. On devices running iOS 8, if a launch file is found, it is used in preference to a launch image. Look in the Project Navigator and you’ll see that you already have a launch file in your project—it’s called LaunchScreen.xib. If you open it in Interface Builder, you’ll see that it doesn’t contain very much (see Figure 2-28).
Figure 2-28. Our application’s default launch file
The default launch file consists of two labels, which Xcode creates automatically using the project and organization names that you entered in the project template selection sheet (see Figure 2-3). Apple recommends that you don’t try to create a complex or visually impressive launch screen so we’re not going to attempt to do that here. Instead, just to show that it works, we’re going to change its background color. To do that, select the View icon in the Document Outline and open the Attributes Inspector. Locate the control labeled Background and choose any color you like—since this is an Apress book, I chose yellow. Now just run the application again to see the result flash by just before the application itself appears.
Figure 2-29. A yellow launch screen for the Hello, World application
You can read more about the launch file, launch images and application icons in Apple’s Human Interface Guidelines document, which you’ll find online athttps://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/IconMatrix.html.
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 6, 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.