Beginning Xcode Swift 3 Edition Edition Knott Download
Beginning Xcode Swift 3 Edition Edition Knott Download
download
https://ebookgate.com/product/beginning-xcode-swift-3-edition-
edition-knott/
https://ebookgate.com/product/beginning-xcode-swift-edition-2nd-
edition-matthew-knott/
https://ebookgate.com/product/beginning-xcode-1st-edition-
bucanek/
https://ebookgate.com/product/beginning-ios-storyboarding-with-
xcode-lewis/
https://ebookgate.com/product/learning-swift-3-early-release-3rd-
edition-jonathan-manning/
iOS 12 App Development Essentials Learn to Develop iOS
12 Apps with Xcode 10 and Swift 4 Neil Smyth
https://ebookgate.com/product/ios-12-app-development-essentials-
learn-to-develop-ios-12-apps-with-xcode-10-and-swift-4-neil-
smyth/
https://ebookgate.com/product/beginning-iphone-development-with-
swift-2-exploring-the-ios-sdk-2nd-edition-david-mark/
https://ebookgate.com/product/beginning-wordpress-3-1st-edition-
stephanie-leary/
https://ebookgate.com/product/beginning-google-maps-api-3-1st-
edition-gabriel-svennerberg/
https://ebookgate.com/product/beginning-c-3-0-an-introduction-to-
object-oriented-programming-1st-edition-jack-purdum/
I nc
Xc
Learn to build powerful iPhone and iPad apps
lu
de
od
using Xcode 6 and Swift
s
e
6
Beginning
v
vi Contents at a Glance
Index .................................................................................................................................525
Introduction
Welcome to Beginning Xcode, the book that aims to give you all the knowledge to start writing
applications using what is probably the most powerful integrated development environment (IDE)
ever. And that IDE is free.
As with many Apple products, Xcode has simplicity and ease of use in abundance, but don’t be
fooled: the shiny exterior masks a workhorse of a tool, incredibly powerful and with an extensive set
of integrated tools for every eventuality. Xcode is the development environment that all other IDEs
have a poster of pinned to their bedroom walls.
Xcode hasn’t always been this shining Rock God of awesomeness; it used to be a sorry band of
ragtag applications. When I first picked up Xcode 3 in 2007, I remember going through a multitude
of different applications to perform varying tasks, such as the very basic Interface Builder, and
finding out how to adapt my knowledge of C into Objective-C. Back then, what I really wanted was
something that showed me how to get the most out of Xcode and could give me the understanding I
needed to get going with the hundreds of app ideas I had in my head.
Fast-forward seven years, and both Xcode and I have come a long way. I feel as if I’ve gone from
being a kid, bumping my leaky paddleboat aimlessly around a lake, to being a handsome sea
captain at the prow of my vessel, gazing forth as I slice through choppy waves with grace and ease.
Well, aside from the handsome part, the analogy is a good one. Xcode 6is more complete and
powerful than ever before: it’s an integrated product that puts in your hands the same power used by
the developers at Apple who write the apps found in iOS and Mac OS X.
I’ve always had a mixed experience with development books and have often been sick of building
the same old apps again and again. In this book I’ve aimed to take you through almost every facet of
Xcode, helping you to understand the capabilities of each of the key areas as you build a number of
cool and exciting projects along the way and come to grips with the new Swift programing language.
By the end of the book, you should be ready to turn the ideas in your head into reality—and I can’t
wait to see what that looks like.
xxi
Part 1
Getting Acquainted
Chapter 1
Welcome to Xcode
Apple provides Xcode to developers to help them create applications for Macs, iPhones, and
iPads (OS X and iOS). Xcode was used to create many of your favorite iOS and OS X applications.
Arguably, without such a powerful, refined, integrated development environment (IDE), the thriving
ecosystem that is the App Store would not exist as it does today.
What Is Xcode?
All developers, regardless of the platform for which they’re developing, use an array of tools to take
an application from an idea to something that is readily available to millions of people. Apple is no
exception, and it provides a cultured, powerful, and polished set of development tools. These tools are
brought together within one application called Xcode. Xcode provides everything you need to create,
test, deploy, and distribute applications for iOS and OS X. With the release of iOS 8 and Xcode 6,
Apple has radically overhauled its toolset and created powerful new technologies that aid developers
in making the process of creating an application fun and rewarding; in addition to that, and for the first
time since Xcode was released, it now supports a brand-new proprietary programming language
called Swift.
The purpose of this book is to guide you in becoming familiar with Xcode 6, in the hope that you’ll
become more confident and embrace it to create amazing, innovative new applications for iOS and
OS X. As in many other technical books, as you progress through each chapter, you build on your
knowledge and systematically create a number of iOS applications.
Although Xcode was created primarily for developers working on iOS and OS X applications, it’s also
great if you work with other languages such as C, Java, and C++, among others. Xcode has a long,
interesting history of releases, some having a very good reception and some less so. First released in
2003, Xcode has had six major releases and seen a couple of major interface overhauls. After more
than 10 years of active development, it’s safe to say that Xcode is incredibly powerful and a leading
professional set of development tools. What’s more, Xcode is available to developers at absolutely
no cost; all you need is an iTunes account, and you’re good to go.
3
4 CHAPTER 1: Welcome to Xcode
What Is Swift?
Before WWDC 2014, Apple’s World Wide Developer conference, if you created a project in Xcode,
the code that was added behind the scenes was written in a programming language called
Objective-C. At WWDC14, Apple unveiled a brand-new and highly streamlined programming
language called Swift. This new language greatly reduced the amount of code needed to achieve
equivalent outcomes in Objective-C. Swift is far less rigid than Objective-C and is very similar in
structure to Python, a move that will no doubt encourage more developers into what is already one
of the most accessible development ecosystems in existence today.
To make Swift even more appealing, Apple also introduced a new piece of software called Swift
Playground with Xcode 6. Playground gives you the ability to experiment with snippets of code
to see the result without putting them into your application, meaning you have a code sandbox in
which to try things such as loops or regular expressions and instantly see the result.
The purpose of this book is to teach you how to create apps using Swift in Xcode 6—it isn’t a definitive
Swift language guide. Apple, however, has released a free book that is a definitive guide to the Swift
programming language and has made it available via iBooks. Search iBooks for Swift programming, or
visit https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11.
Prior Assumptions
Before you dive in and start reading this book, it’s assumed that you have at least some familiarity
with developing for Cocoa Touch and are familiar with the concepts of object-oriented programming.
This book is geared toward those developing for iOS; however, it’s possible to get a lot out of this
book if you’re developing OS X applications, because many of the principles presented can be
applied to either platform.
CHAPTER 1: Welcome to Xcode 5
It’s assumed that you are using a Mac and are preferably running the latest version of OS X. Unlike
the Objective-C based equivalent of this title, it’s absolutely necessary that you run the latest version
of Xcode. This book is written specifically for Xcode 6 and Swift, and the technology doesn’t exist
in previous versions of the IDE. There is a common misconception that you need the greatest and
latest “souped-up” Mac, but many previous-generation iMacs, MacBooks, Mac Minis and Mac Pros
will work just fine.
It’s also assumed that you know how to operate your Mac and how to use OS X. For example,
you need to know how to use the Finder, save files, and so forth—all the basics. Finally, a couple
of the chapters present scenarios in which an active Internet connection is required, and some
features of Xcode perform better when you’re connected. Additionally, some later chapters require a
physical device and a paid developer account to complete, but for the most part you can use an iOS
simulator to run your apps.
It’s also worth mentioning that the purpose of this book is not to teach you how to create
applications for iOS or teach you how to program in Swift or Objective-C; the purpose of this book
is to get you up and running with Xcode so you can apply your current knowledge of Swift and OS
X/iOS development and use the latest version of Xcode to its full potential to enable you to work
more productively and create fantastic applications.
A final note, this book was written at a time of transition, when OS X 10.10 Yosemite was not
released. All screenshots are taken using OS X 10.9. Despite being the same version of Xcode, there
are differences in icons between the versions, and when this happens I call it out.
Chapter 5: Next, you’re shown how to access the invaluable help resources that
are built right in to Xcode and also how to make the most of its intelligent
code-completion feature.
Chapter 6: Building on Chapter 4, you see the Auto Layout system and learn
how it works with constraints and the new size classes introduced in Xcode 6 to
create a single layout for any device.
Note If you don’t have access to the latest version of OS X or are running an older version that isn’t
supported, you can download previous versions of Xcode from the iOS Dev Center, but for this you need
to have a registered Apple developer account. This is explained later. However, this book covers the latest
version of Xcode (which is 6.0 at the time of writing).
Select the icon, and you’re taken to Xcode’s App Store page. Here you can view all the features of
Xcode along with the latest additions to the current version of Xcode (at the time of writing, this is
6.0) and also preview some screenshots of Xcode. To download Xcode, click the gray Free button
and enter your Apple ID e-mail address and password, and your download will commence. Xcode
is about 2.4 GB, so you can go and make some coffee while you wait for the download to finish, as
shown in Figure 1-2.
8 CHAPTER 1: Welcome to Xcode
With Xcode downloaded, open it from your Applications folder. You’re prompted to install some
additional packages: click Install, and enter your user password. This installation should take a
matter of seconds, as shown in Figure 1-3.
CHAPTER 1: Welcome to Xcode 9
Firing Up Xcode
Once you’ve successfully downloaded and installed the additional components, you can begin using
Xcode. In Chapter 2, you create your first project and become familiar with the basic areas of Xcode;
but for now, just make sure everything is in good order so you don’t encounter any problems later.
When you first launch Xcode, you’re presented with a Welcome splash screen. From here you can
create a new project, connect to an external repository, open documentation, visit Apple’s developer
portal, and also browse a list of your recent projects. For some, this screen causes irritation—you
can prevent it from appearing each time you open Xcode by simply checking or unchecking the
Show This Window When Xcode Launches box, as shown in Figure 1-4.
10 CHAPTER 1: Welcome to Xcode
Figure 1-4. Xcode’s Welcome window, which is displayed optionally each time you open Xcode
To create a new project, you can click the Create A New Xcode Project button on the Welcome
screen or navigate to File ° New ° Project, where you’re presented with a range of templates
provided by default by Xcode.
If you have gotten to this point, it’s safe to assume that you’ve successfully installed Xcode and that
you’re ready to start creating projects. However, let’s save this for a deeper explanation in Chapter 2
and for now look at the variety of resources provided to developers by Apple.
First, head over to http://developer.apple.com. This is the central web site for Apple developers.
On the home page of the site, click iOS Dev Center. The iOS Dev Center is the central location
for all the resources provided to those who create iPhone, iPad, and iPod Touch applications, as
shown in Figure 1-5.
Figure 1-5. The iOS Dev Center—home of Apple resources for iOS developers
You aren’t required to sign up in order to gain access to many of the resources, including the
Developer Library, an overwhelming wealth of example source code, release notes, and many more
things. You can happily browse through the iOS Dev Center right now.
However, there are great advantages to signing up as a registered Apple developer, and it will
become essential at some point if you’re planning to distribute applications via the App Store.
Therefore, it’s a good idea to sign up right from the start. To begin the process of signing up,
click the Register For Free text just below the Sign In button; alternatively, you can visit
http://developer.apple.com/programs/register/. In order to sign up, you need a valid Apple
ID; if you don’t have one or would like to dedicate an Apple ID to your developer account, create
a new one (don’t worry, none of your purchases or downloaded content from the App Store or
iTunes Store will be affected if you use your current one).
Once you’re happy with your Apple ID, go to http://developer.apple.com/programs/register/
and sign up for an account. In order to complete the process of signing up, you need to create a
personal and professional profile; you can change these at any time if you need to.
12 CHAPTER 1: Welcome to Xcode
You’re required to complete your professional profile by telling Apple any previous platforms
you’ve developed for along with your primary markets and experience with Apple’s platforms.
This information is used by Apple to get an idea of the spectrum of people who are signing up as
developers. Again, once you have completed this, click the Next button. Also, it’s important to note
that what you select when updating your professional profile doesn’t bind you to anything, and that
you’re able to develop and release applications to any of the App Store’s markets. Furthermore, you
can, if needed, make any amendments to your professional profile (and personal profile, for that
matter) after you’ve signed up, as shown in Figure 1-6.
Finally, you reach the tiresome agreement that comes with many of Apple’s products; read it, click
to agree, and then continue with the process. To finish, all you need to do is verify that the e-mail
address supplied is valid; you do this by opening the e-mail sent to you by Apple and entering the
verification code contained within.
CHAPTER 1: Welcome to Xcode 13
In addition to the iOS Developer Library, you also have access to an array of getting-started
videos that explain core Objective-C and Cocoa Touch concepts. You’re also given access to
a direct link to the latest version of Xcode on the Mac App Store and the ability to download
previous versions of Xcode if you’re not running the latest version of OS X or would like to target
older versions of iOS.
14 CHAPTER 1: Welcome to Xcode
It’s useful to note that when you’re prompted to choose between an individual or company account,
if you’re planning to operate under a name other than your own, you have to register as an official
company (this is verified by Apple) and then acquire what’s called a Data Universal Numbering
System (DUNS) number that uniquely identifies your company; this takes around 7 days to process,
so plan ahead. If selling applications under your own name suffices, then go for the simpler option of
signing up as an individual; both accounts are essentially equal in terms of the resources you’re able
to access. This choice mainly determines the name with which you operate under on the App Store.
Don’t worry if you’re not ready to do this right now—it’s covered in detail later in the book when it
becomes essential if you’re planning to release applications on the App Store (free or paid) or want
to test your apps on an iOS device. Chapter 14 looks at using Provisioning Profiles and deployment
onto actual iOS devices as opposed to the virtual iOS Simulator, so you then need access to a paid
developer account.
Source Code
I strongly recommend that one of the first things you do is to go to the Apress web site for this
book and download the entire source code. Either search for the book at www.apress.com or go
directly to www.apress.com/9781430250043. When you get to the page for this book, scroll down
until you see the section of the web site with four tabs, the third of which is Source
Code/Downloads, as shown in Figure 1-9.
Figure 1-9. The source code download page for this book
Additional Resources
In addition to Apple’s own resources, an extensive amount of third-party resources are available if
you ever have a burning question or get stuck somewhere:
Forums: Forums are a great way to ask questions, learn from other people’s
questions, and help other people. In particular, Stack Overflow
(http://stackoverflow.com/) has been invaluable to the entire developer
spectrum for years and has a vibrant, active collection of iOS developers.
There are also the Apple developer forums, which are available to those
with a paid Apple developer account.
16 CHAPTER 1: Welcome to Xcode
Mailing lists: There’s a handy Xcode users mailing list that I’d recommend you
subscribe to and periodically check. Many other developers, including myself,
participate in answering questions relating to Xcode. You can subscribe at
https://lists.apple.com/mailman/listinfo/xcode-users.
Xcode Overview: Apple provides a handy user’s guide that’s always being updated
to accompany the latest release of Xcode, so it’s a good idea to refer to it when
there’s a new update or if you’d like to follow up on something. It’s available at
https://developer.apple.com/library/ios/documentation/ToolsLanguages/
Conceptual/Xcode_Overview. Similarly, it’s also handy to glance over the latest
release notes when Xcode is updated. These are available at https://developer.
apple.com/library/ios/releasenotes/DeveloperTools/RN-Xcode.
Search engines: It’s easy to underestimate the power of a simple Google search
(and it’s apparent many people on online forums don’t have access to them).
It can save you a lot of time, because someone, somewhere, at some point has
undoubtedly had the same question you do—all you need to do is find where they
asked it!
Videos: If you type “Xcode” into iTunes U search, you’ll find a couple of good
university courses that focus not only on Xcode but also on iOS development in
general. Similarly, type “Xcode” into YouTube search, and you’ll be amazed at
what you can learn from the short screencasts that have been uploaded.
Contact me: I am happy to field questions via email at [email protected] or via
my blog at www.mattknott.com.
Summary
In this chapter, you have:
Successfully downloaded and installed Xcode
Had a look around the iOS Dev Center and also looked at the resources
provided by Apple to aid developers
Signed up and registered as an Apple developer and become aware of the
option of signing up for a paid developer account
Chapter 2 explains how to create your first project and helps you become more familiar with Xcode’s
interface and basic concepts.
Chapter 2
Diving Right In
In Chapter 1, you downloaded Xcode, made sure it was correctly configured, signed up for a
developer account, and explored the wealth of resources provided by Apple to help you get started
with not only Xcode but also some of its fantastic new technologies. This chapter explains how
to create a working application using Xcode’s visual interface building tool (aptly named Interface
Builder) and its built-in code editor and then run the app on your machine.
As mentioned, as you progress through this book, the ultimate goal is not only to get a grip on the
latest and greatest version of Xcode but also, by the end of the book, to have walked you through
building a series of varied applications that give you many of the essential skills needed to go out
and start writing your own applications. The application you build in this chapter familiarizes yourself
with Xcode as a development environment before you start looking at sharing data between pieces
of your application in Chapter 3. For now, you develop a very simple application that has a custom
background color and a label, and you programmatically update the text in the label.
Be forewarned that in this chapter, a lot of the concepts are new and therefore require more
explanation to do them justice. As a result, on several occasions you’re told that later chapters revisit
many of the concepts presented. This is because the main goal of this chapter isn’t to turn you into
an Xcode pro, but rather to get you started and give you the confidence to believe that Xcode isn’t
as overwhelming as it may first appear. In Figure 2-1, you get a glimpse of the example application;
although simple, it will make you at least a little familiar with the workings of Xcode and help you to
understand that Xcode can help you produce a working application in next to no time.
17
18 CHAPTER 2: Diving Right In
Figure 2-2. The variety of different templates provided by Apple to help you get started with creating your app quickly
You need to specify a couple of things before you can actually get started. Once you select your
project template, a screen identical to that in Figure 2-3 is displayed. Following is a brief overview of
each of the values required to proceed—bear in mind that you learn more about the significance of
some of the values you enter here as the book progresses:
Product Name: What you would like to call your application. For example, if you
wanted to create an application called Chocolate Recipes, you’d specify the
Product Name to be something along the line of Chocolate Recipes. Although
not required, it’s generally good practice to omit any spaces and instead
capitalize each new word. The Product Name can be amended during the
development of your application, so you’re not obliged to stick with what you
specify; but regardless, the Product Name is a rather important detail that you’re
required to specify at this stage.
Organization Name: Required whether you’re working independently or you’re
part of a software development company. For now, your own name is adequate.
If you’re looking to submit an application to the App Store, it’s in your best
interest to specify the correct name; although not required, it’s recommended.
When you create a new file, your Organization Name automatically appears
along with copyright details at the top; that’s something to bear in mind if you
plan to work on a team or hand your project off to someone else.
Organization Identifier: Only really required if you’re planning to distribute your
application in some capacity. For example, to distribute an app via the App
Store, you’re required to specify an App ID along with a Bundle Identifier, which is
created by Xcode depending on what you input as your Organization Identifier. The
company identifier is written in the style of reverse domain name notation; my web
site, for example, is mattknott.com, so my Organization Identifier is com.mattknott.
20 CHAPTER 2: Diving Right In
Note If you’ve been using an older version of Xcode, you may have an annoying feeling that a field is
missing. In version 6 of Xcode, Apple decided to remove the ability to specify a Class Prefix value. The Class
Prefix was added to the start of every new class you created to help differentiate your classes from other
class files that might be imported into the project.
3. Now that you vaguely know what these values are for and what they
correspond to, you’re probably wondering what you should input to create
this project. As shown in Figure 2-3, type in HelloWorld as the Product
Name; input your own first and last name as your Organization Name;
use com.LASTNAME as your Organization Identifier (obviously change
LASTNAME to your actual last name), set the Language value to Swift if it
isn’t already, specify iPhone as the Device, and, finally, ensure that Use Core
Data isn’t selected.
4. Once you’ve made sure all your values are correct, click Next. You’re required
to save your project to disk.
5. When prompted to, use the familiar OS X dialog to find a location. Make sure
the box next to Source Control For This Project is unchecked, and then click
Create.
Note Git is a popular system used for version control and source-code management. You can integrate a
local Git repository with a web site such as GitHub or Bitbucket if you want to back up or share your code
online. If none of these things are familiar to you, Chapter 12 explains.
So, you’ve given Xcode all the relevant details and specified what kind of project you’re looking to
create. As a result, Xcode conveniently creates a basic, functioning application for you to use as a
starting point. The code that Xcode creates for you is just enough to get the application to run; it’s a
working, if slightly pointless, app that you can run right now if you like.
Choose Product ° Run (Ɖ+R), and you’ll find the application builds successfully and the iOS
Simulator pops up with the app running, as shown in Figure 2-4. It’s nothing spectacular, nor will it
reach the top 25 in the App Store anytime soon, but it’s a functioning application created by Xcode
with very little input from you. Return to Xcode, and click the Stop button in the top-left corner or
choose Product ° Stop (Ɖ+.).
22 CHAPTER 2: Diving Right In
Tip With the high resolution of modern iOS devices, unless you have a top-of-the-range Mac, the simulator
may be too large for your computer screen. If this is the case, then with the simulator selected, choose
Window ° Scale ° 50% or use the key shortcut Ɖ+3. The Scale menu also gives you the option to go to
100% or 75% scale using Ɖ+1 or Ɖ+2, respectively.
CHAPTER 2: Diving Right In 23
The Project
In order to make the app a little more interesting than a simple white screen, you need to open some
files that Xcode created. As with previous versions of Xcode, the way in which it organizes your
project’s file is somewhat strange. Upon returning to Xcode, if you look to the left of the interface,
you should see what appears to be an arrangement of folders and files. These are the files that make
up your project (see Figure 2-5). This part of Xcode is called the Project Navigator. If you’re unable
to find it, choose View ° Navigators ° Show Project Navigator (Ɖ+ 1). It’s important to note that
when you create a folder in the Project Navigator, it doesn’t correspond to the structure in which the
files are saved in the Finder. The folders and organization of the Project Navigator are purely to help
you locate files in Xcode. If you create a folder in the Navigator, the same folder isn’t present in your
project when you browse in Finder. I revisit this when you add a file to your project later
in this chapter.
If you’ve used Xcode with Objective-C in the past, then you’ve almost certainly noted that when
using the Swift language, there are far fewer files in the project. The reason is that in Objective-C,
each class file is created with a header (.h) file and an implementation (.m) file. Swift combines all
class information into a single file.
With that in mind, select Main.storyboard from the Project Navigator. Xcode opens its built-in
graphical user interface (GUI) design tool, usually referred to as Interface Builder. Xcode 4.0
represented a major overhaul of Apple’s developer tools: Interface Builder, which was previously a
separate application, was conveniently integrated into Xcode, making it easy to switch between the
built-in code editor and interface design tool in a single application, as shown in Figure 2-6. One
warning is worth mentioning: the more you become familiar with Xcode, the more you may wish
for a larger screen!
Figure 2-7. Changing the view’s background using the Attributes Inspector
26 CHAPTER 2: Diving Right In
3. Add a label to your view. To do this, open the Object Library (shown in
Figure 2-8), and drag a label object to your view. Generally, the Object
Library is right below the Attributes Inspector and accessible by selecting the
third tab; you can also access it via View ° Utilities ° Show Object Library
(Ƃ+Ɖ+ƃ+3).
4. With the library open, use the small search bar to search for “label”.
5. Once you’ve found the label object, drag it to your interface at the top of
the view, as shown in Figure 2-9. As you position the label near the top, the
Guides shown in Figure 2-9 appear, and the label snaps into place.
CHAPTER 2: Diving Right In 27
Note Regardless of whether you’ve used Xcode before, you may wonder why you’re only seeing what
appears to be the top portion of the device’s screen. This is because of a new Auto Layout feature that Apple
introduced with Xcode 6 and iOS 8, called Size Classes. I explain in greater detail later in the book.
6. Select your new label, and use the handles to extend its size so it fills the
width of the View. Then double its height to accommodate a larger font size.
7. Set the Alignment attribute in the Attributes Inspector to Center.
8. Click the T symbol in the Font attribute to alter the font. Set Font to Custom,
Family to Avenir, and Size to 32, as shown in Figure 2-10.
28 CHAPTER 2: Diving Right In
9. Because you have Size Classes enabled for this view, it’s essential to set a
couple of parameters called constraints that tell iOS how to position the label
in the view. I cover this in detail later in the book, but for now, locate the pin
icon in the bottom-right corner of the design area and click it. A popover
appears.
10. At the top of the pin popover, you see a square with an I bar on each side
followed by a numeric value. Click the top, left, and right I bars to highlight
them red, as shown in Figure 2-11. Then click the Add 3 Constraints button.
At this stage, although you can use the Attributes Inspector to specify the text to be displayed in the
label, it’s important to realize that Xcode isn’t just about creating graphical interfaces. It also houses
a very powerful code editor. So, as you progress through this chapter, you update the contents of
your label programmatically as opposed to graphically.
Making Connections
Before you leave Interface Builder and move on to focus on Xcode’s code editor, let’s look at a
powerful feature that allows you to use both simultaneously. Open the Assistant Editor by selecting
the shirt-and-bowtie icon in the top-right corner of Xcode, as shown in Figure 2-12, or by selecting
View ° Assistant Editor ° Show Assistant Editor (Ɖ+ƃ+Return).
Figure 2-12. The button to select the Assistant Editor looks like a shirt with a bowtie
Opening the Assistant Editor splits your screen, with Interface Builder occupying the left frame and
the code editor occupying the right (unless you’ve customized this appearance, as I show you later
in the book). Before you continue, you need to make sure Xcode has opened the correct file. You
should be looking at a file called ViewController.swift: you can verify this by looking at the jump
bar just above the code, as shown in Figure 2-13. Continue as follows:
1. With both Interface Builder and the code displayed using the Assistant Editor,
click the label you added to your view in Interface Builder to highlight it.
Figure 2-13. The jump bar in the Assistant Editor shows which file is open
30 CHAPTER 2: Diving Right In
Now you’re going to create a variable called an outlet (IBOutlet) to make the label accessible
through your code. In older versions of Xcode, the process of creating an outlet and then wiring it
into Interface Builder was quite long-winded, but Apple has simplified this greatly over the past few
versions of Xcode by allowing you to drag connections directly from Interface Builder into the code.
2. Holding down the Control key, click the label and drag a connection to the
ViewController.swift file. Position the cursor in the class scope, just
below the line class ViewController: UIViewController {, as
shown in Figure 2-14.
When you release the mouse button, a Connection dialog appears, asking for a number of values
(see Figure 2-15). The key option you need to be aware of here is the Name text field. If the object
you’re connecting to code can be tapped or trigger an event, you can choose one of two options for
your connection: Outlet or Action. But in this instance Xcode intelligently knows that this label isn’t
interactive and therefore restricts your choices.
3. The Name text field value determines how you refer to your label in code. For
now, type in lblOutput and click Connect.
If everything’s gone according to plan, the first few lines of code should look like this:
import UIKit
4. You’re finished with the Assistant Editor for now, so switch back to the
Standard Editor by selecting the icon from the toolbar with three lines in a
box, to the left of the Assistant Editor icon (see Figure 2-12).
You’ve finished with Interface Builder for this project. Now you need to write some code to
manipulate your label. Go to the Project Navigator and select ViewController.swift. The View
Controller’s class file opens in the code editor, as shown in Figure 2-16. This chapter touches on
many areas and concepts I explain throughout the book; but at this point, you’re going to start using
Xcode’s powerful code editor and see some of the intuitive features that make Xcode one of the best
IDEs ever.
Figure 2-16. Xcode’s built-in code editor with the ViewController.swift file open
32 CHAPTER 2: Diving Right In
With the class file open, notice that it has a number of lines of code by default. This boilerplate code
gives the application a starting point you can build on.
In the code of the class file, look for a line that begins with override func viewDidLoad(): this is the
start of the viewDidLoad function. To complete the very simple code for this application, you need to
tell the View Controller that when the view loads, it should set the label’s text to “Bonjour!”. Add the
highlighted code to the viewDidLoad function, as shown:
lblOutput.text = "Bonjour!"
}
Here you can see Xcode’s powerful code-completion feature in action; it can assist you in writing
code much more efficiently. As you type lbl, a pop-up appears that says UILabel! lblOutput; when
this is highlighted, press the Tab or Return key to complete the word lblOutput. Next type .te. Again
Xcode’s code completion snaps into action and shows a number of options, but the first one in the
list is the one you want: String! text. With that item selected, press Return and continue typing
the code. You can easily see from this example how Xcode’s code completion helps you become a
really efficient programmer, as well as how it helps cut down on errors.
To recap, what you’ve done here is to declare a variable that is linked to the UILabel you added to
the view in Interface Builder using the Assistant Editor. You then added a single line of code to the
viewDidLoad function to set the text of the label programmatically—well done!
or an iPad. Applications may not perform the same on a device as they do on iOS Simulator,
because the simulator doesn’t simulate all software and hardware functionality. To change the type
of device you’d like your application to be tested on via the iOS Simulator, go back to Xcode and
click the Stop button in the top-left corner. With the application no longer running, go back to the
iOS Simulator and choose Hardware ° Device, and then select from the list of devices available.
Figure 2-17 shows the application running in the iOS Simulator.
Figure 2-17. The iOS Simulator running the app using the iPhone 5s as the simulated hardware
34 CHAPTER 2: Diving Right In
Additionally, in the iOS Simulator you can change the orientation of the device, the scale at which
the device displays, and an array of other options covered later in this book. What’s recommended
now is that you browse through the menus of the iOS Simulator while your app is running and play
around with the options to get a little familiar with the different features.
Adding Files
One final thing worth mentioning at this early stage is how to add your own files to your project.
Applications can be made up of literally hundreds upon hundreds of files, ranging from images to
sounds. Let’s add some images to the example application: let’s change the app’s icon without
writing any code and then add a background image to the main view.
Before you add an icon file, you either need to create one or download the source code for this
book from the Apress web site and use the included files. Because this isn’t a book on iOS design
or even iOS development, I won’t digress about how to create perfect iOS app icons. Instead, I’ll
just state that you need to create a PNG file that, in this instance, I’m calling icon120.png, with
dimensions 120 px by 120 px. Include whatever you like as the graphic, making sure it conforms to
these specifications. I created a file with a basic gradient and a speech bubble saying “Hi!” in the
middle. To set the application icon, you work with a feature that Apple introduced in Xcode 5, called
Asset Catalogs; these are covered in more detail later in the book, but suffice to say they make the
headache of managing retina and standard-resolution images far easier than having a folder with lots
of different-sized images. Here are the steps:
1. From the Project Navigator, select Images.xcassets.
2. You’re presented with two items in the left column of the Asset Catalog. Click
AppIcon.
3. Bring the Finder window with the icon file in it over the top of Xcode, and
then drag the icon file to the box labeled iPhone App Icon iOS 7 60pt, as
shown in Figure 2-18.
Figure 2-18. The Images Asset Catalog where you set the application icon
CHAPTER 2: Diving Right In 35
Run the application to see the icon in action. Once the app is running, choose Hardware ° Home
(Ɖ+ Shift+H). If you’ve done everything right, you should see something like the image in Figure 2-19.
Note As you’ll learn as you progress through the book, Apple requires you to create icons in numerous sizes
for the App Store, currently including up to 1,024 pixels square. It’s good to get into the habit early of adding
the resolution to the filename to help you keep track of your assets.
With the icon successfully set, let’s look at another, more traditional way of adding files to the
project. (You expand your Asset Catalog knowledge later in the book.)
They say there’s more than one way to skin a cat, and the same can be said for accessing Xcode’s
Add Files dialog. First, you can choose File ° Add Files to “HelloWorld” (Ɖ+ƃ+A), or you can right-
click in the Project Navigator area and choose Add Files to “HelloWorld”. But the method I want you
to use is to click the plus icon in the bottom-left corner of the Project Navigator and then click Add
Files to “HelloWorld”, as shown in Figure 2-20.
Figure 2-20. The Add Files dialog available from the Project Navigator
36 CHAPTER 2: Diving Right In
The Add Files dialog will be instantly familiar to any user of OS X. Now you need to locate an image
file you would like to use as the application background. In this example, I have downloaded an
image from the fantastic website www.unsplash.com, which has a collection of images licensed under
the Creative Commons license (they’re public domain). The image is included with the downloadable
resources for this chapter.
Once you’ve located your file, select it, and then make sure Copy Items If Needed is checked, as
shown in Figure 2-21. Click Add.
Figure 2-21. The Add Files dialog. Note that Copy Items If Needed is checked
At this point you return to Xcode. Look at the Project Navigator, where you see that your file has
been added to the project’s file structure. When I asked you to add the file, I also asked you to
ensure that Copy Items If Needed was checked. The reason is that if you don’t check this option,
the file appears in the project structure as it does now, but the file itself isn’t copied into the project.
Hence, if you were to send the project to someone or to archive it, the image would be omitted.
CHAPTER 2: Diving Right In 37
Figure 2-22. The structure of the files in the Project Navigator in Xcode (left) compared to those in Finder (right)
As you can see, there are some similarities, but there are items that are visible in one view and yet
hidden in the other. This peek behind the scenes teaches you that what you see in Xcode may or
may not physically exist on your file system.
You’ve done the hard work of adding the file to Xcode. Now let’s do the fun part—adding the image
to the View Controller using the Storyboard. Start by selecting Main.storyboard from the Project
Navigator. Now, from the Object Library, select an image view (UIImageView) object, and drag it to
your View Controller. If you’re having trouble finding it in the list, remember that you can filter the list
by typing “image” in the search field. Resize the Image View so it fills the entire view. Your screen
should look something like Figure 2-23.
38 CHAPTER 2: Diving Right In
Figure 2-23. Adding the image view and resizing it to fill the view
Tip Remember, if you can’t see the Object Library, you can access it via View ° Utilities ° Show Object
Library (Ƃ+Ɖ+ƃ+3).
With the image view positioned, it’s time to specify which image to use:
1. With the image view selected, go to the Attributes Inspector.
2. From the Image drop-down, select the file you added. If you’re using the
image from the download, then this is the file starting with jNgy.
3. The image fills the image view, but it may have been distorted in doing so.
You want the photo to fill the image view but maintain its ratio. To achieve
this, click the Mode drop-down list, and change it from the default Scale To
Fill option to Aspect Fill. Your image still fills the image view, but the ratio is
maintained, preserving the original look of the image.
CHAPTER 2: Diving Right In 39
4. You once again need to apply constraints, this time to the image view.
Ensuring that the image view is still selected, click the Pin button at the
bottom of the design area. This time, all four values should say 0; if they
don’t, change the values to zero and then click all four I bars as shown in
Figure 2-24. Click the Add 4 Constraints button.
So you’re finished, right? Not quite. With the image view filling all the available space, you can’t
see the label you added at the start of the project! This is because of the way these two items
are ordered, or rather how they’re layered: the image view is rendered in a layer above the label,
obscuring it. To resolve this, let’s look at the Document Outline. If you can’t see the Document
Outline (the column between the design area and the Project Navigator), click the Show Document
Outline button in the bottom-left corner of the Storyboard design area, or choose Editor ° Show
Document Outline.
Expand all the items in the Document Outline. Beneath View, you should have your label, followed by
the image view. Drag the image view carefully to move it above the label, as shown in Figure 2-25.
Because of the hierarchy of the objects in the view, the image view is now rendered beneath the label,
although you may need to tweak the color of your label to make sure it’s visible against the image
background.
40 CHAPTER 2: Diving Right In
Figure 2-25. The Document Outline after rearranging the order of the elements in the view
You’re ready to run your app! Figure 2-26 presents the finished product.
CHAPTER 2: Diving Right In 41
“I’m sorry, Grubb, I’m awful sorry the rifle went off
—’cause I’ve got a big scolding from papa and the
admiral, too. But you hadn’t any business touching the
flag; you know you hadn’t. Come around next Saturday
morning and I’ll give you my half-dollar.”
“Hello, Capps!”
But Capps did not move. His eyes were closed, and 27
Young Brydell, after playfully prodding him with a slate
pencil, went his way. Presently he met Cunliffe, who
also saw the old sailor sitting so still upon the bench.
The two boys each turned a little pale. This was their
first knowledge of that unknown thing called Death.
Next day Capps was buried. Ensign Brydell and one or
two other officers walked in the old boatswain’s funeral
procession. He had always said he wanted “a rale lively
funeral, like as a sailor man is got a right to,” and he
was gratified. The plain coffin rested on a caisson, and a
squad of sailors and marines marched behind it with the
band playing.
“For it’s the honor you did poor old Capps,” said Grubb 30
to Young Brydell.
33
CHAPTER III.
BRYDELL’S FIRST FAILURE.
Just six years after the May day that Young Brydell had
nearly shot Grubb’s ear off, on a day as bright, he sat
with a number of other young fellows about his own
age around a long table, answering the questions of
three professors who were examining them. Each had a
great stake in this examination, as it was for an
appointment to the naval academy at Annapolis.
40
This last reflection brought Brydell suddenly to himself.
He remembered poor Grubb’s giving his boy half his
pay. “And my poor old dad—poor young dad, rather—
gave me, I believe, a good deal more than half his pay.”
“By!”
“By!”
45
CHAPTER IV.
BRYDELL’S SECOND FAILURE.
The weeks since his failure had been spent in a dull and
hopeless mental lethargy. Aunt Emeline had been grimly
consolatory and had tried to impress on him that he had
made a lucky miss in not getting into the navy, and
named at least a thousand professions and business
ventures in which he could make more money. The
good woman did not see in the least how it was with
the boy—that he was simply born to be a sailor, and
that nothing on earth could charm him then from his
wish.
“Mr. Brydell, please don’t go for to tell it, sir, but Mr.
Esdaile—Mr. Esdaile is my son. His grandfather’s left him
some money, if he’d take the same name—Esdaile; and
as the boy didn’t like the name o’ Grubb, nohow, he got
his name changed by law—and I’d ruther—I’d ruther, sir,
the folks here didn’t know it, bein’ as I ain’t nothin’ but
a marine.”
“Didn’t I tell you, sir, long years ago as how the boy was
gittin’ above his father?” burst out poor Grubb, his eyes
filling with tears. “He’s ashamed o’ me; he’s ashamed to
be seen a-talkin’ with me, and I can give him half my
pay, and I’d give him all o’ it if he needed it, but I can’t
stand bein’ looked down upon by him.”
GEORGE BEAUMONT.
The day was dark and rainy, but no June morning ever
seemed brighter to Brydell when he read that dispatch.
The transition seemed to him like passing from death to
life.
(sanguine Brydell)
57
CHAPTER V.
STRIKING OUT FOR HIMSELF.
64
The farmer, being compelled to stay indoors, was not
indisposed to talk with the young stranger, and Brydell
had quite a gift of making himself agreeable. They sat
talking in a large, airy, old-fashioned hall, with a dry
rubbed floor; and the little girl Minna was so pleased
with her new acquaintance that she came and perched
herself on the arm of his chair and gazed fearlessly into
his eyes with the grave scrutiny of an innocent girl.
“For what?”
“I ain’t got any work for you;” and after another pause:
“I think it’s clearin’ up.”
ebookgate.com