Even though we've already learned quite a bit in this series on iOS development, I'm sure you are eager to start building iOS applications that do something cool or useful. In this tutorial, your wish is granted. Using Xcode, you'll create an iOS project from scratch, modify the project's source code, and run your application on either the iOS Simulator or a physical device.
Colorific
Colorific is the name of the application that we're about to build. The idea behind Colorific is simple, every time the user touches the screen of the device, the color of the screen changes. Even though the concept is basic, Colorific is perfect for getting started and exploring the ins and outs of iOS development.
1. Create a New Xcode Project
As we saw earlier in this series, every iOS application goes through life as an Xcode project. What is an Xcode project? An Xcode project is a container or repository that contains the files, assets, and information that are required to build one or more products.
Note that this isn't limited to a project's source code and assets, such as images and other media. A project also keeps track of the connections between its various elements and it knows how to build the final products from its elements.
Fire up Xcode and create a new Xcode project by choosing New > Project... from the File menu. An alternative option is pressing Shift + Command + N
.
In case Xcode's welcome window pops up when you launch Xcode, I suggest to close it so you learn how to create a new project using Xcode's menu.
2. Choose an Application Template
Getting started with a new application or project is easy in Xcode thanks to the application templates that come with it. For the application that we're about to create, we need the Single View Application template. Feel free to take a look at the other application templates, but make sure to choose the Single View Application template for Colorific.
3. Configure the Project
After selecting the Single View Application template and clicking the Next button, Xcode presents you with a list of options allowing you to configure your new project. Let's take a look at the various options.
- Product Name: The product name will be the name of your application. I have named my application Colorific, but feel free to name your application whatever you'd like.
- Organization Name: The organization name can be your own name or the name of your company. Xcode uses the organization name for various purposes, such as adding a copyright notice to each source file.
- Company Identifier: The company identifier is a unique string, which Xcode uses (together with the product name) to create the application's bundle identifier. Apple recommends adopting the reverse-domain naming convention in an attempt to make this unique. Note that the domain that you use has no tie to the DNS system or Internet domain names. For example, my company is named Code Foundry and is located in Belgium, which means that my company identifier is be.codefoundry. However, I could just as well use be.code-foundry or com.codefoundry. For the purpose of this tutorial, I've set the company identifier to com.tutsplus.
- Bundle Identifier: Even though you cannot specify the bundle identifier when creating a new Xcode project, you can change it once you've created your project. By default, the bundle identifier is the combination of the company identifier and the product name. Keep in mind that spaces in the product name are replaced with dashes in the bundle identifier, because the bundle identifier mustn't contain whitespace.
- Class Prefix: When creating custom classes in your project, it's important that the class names don't collide with existing class names. By specifying a class prefix, Xcode will prefix new classes with this custom class prefix to make sure that naming collisions are averted. A common approach is to use your initials, BJ in my case, or a combination that refers to your company or organization, such as TSP for Tuts+.
- Devices: In the current version of Xcode (5.1 at the time of writing), the devices drop down menu contains three options, iPad, iPhone, and Universal. This configuration option tells Xcode which devices your project targets. By selecting the last option, Universal, your project targets both the iPad and iPhone device family. The iPod Touch is a member of the iPhone device family as you might have guessed.
You should now have a good grasp of the different configuration options when setting up a new Xcode project. For this project, I recommend that you use the options as shown in the above screenshot. Note that most options can easily be changed after you've created your project. Click the Next button when you're finished configuring your project.
4. Save the Project
In the next step, Xcode asks where you want to save your new project. You may have noticed the little checkbox at the bottom of the window labeled Create a git repository on My Mac. The gray text below the checkbox reads Xcode will place your project under version control.
As I mentioned earlier in this series, source control is indispensable in software development. This series will not cover this topic in detail, but if you're serious about software development, then I highly recommend reading up on source control.
Git is the most popular SCM (Source Code Management) system in the Cocoa community. However, it's perfectly possible to use a different SCM system, such as SVN or Mercurial.
Tell Xcode where you want to save your project, check the checkbox to authorize Xcode to create a git repository for the project, and click the Create button.
5. Exploring Xcode's User Interface
Before we move on, I want to take a few minutes to explore Xcode's user interface. You can see four distinct areas:
- a toolbar at the top
- a sidebar on the left
- a main view in the center
- a sidebar at the right
Toolbar
The toolbar at the top contains the buttons and menus that you'll find yourself using often. As we saw earlier in this series, the buttons to run and stop an application live in the toolbar.
The display in the center of the toolbar is similar to the display you find in iTunes. It displays information about your project's state, for example, it will tell you when a build succeeds or fails.
The two segmented controls on the right of the toolbar can be used to customize Xcode's user interface. Play around with the various controls to find out how each of them changes Xcode's user interface.
Navigator
The main purpose of the left sidebar is for navigation and it's often referred to as Xcode's navigator.
The navigator has different tabs with the Project Navigator at the far left. The selection in the left sidebar determines what is shown in Xcode's main view, the workspace.
Main View or Workspace
The main view or workspace is the area where you'll spend most of your time. It's Xcode's workhorse and displays whatever's selected in the navigator.
Inspector
While the left sidebar controls what's being displayed in Xcode's main view, the contents of the right sidebar reflects what's being displayed or selected in the main view.
The right sidebar, also known as the inspector, adapts itself to whatever the user selects in the main view.
6. Exploring the Project
It's time to take a look at the project itself. The project's contents are displayed in the Project Navigator, the first tab in the left sidebar. Select the first item in the Project Navigator to see the project details in the main view.
The main view is composed of two sections, a sidebar on the left and a detail view on the right. In the sidebar, you see two items, your project with one item and targets with two items.
It's good to know early on what the difference is between a project and a target. As I mentioned earlier, a project is a repository for the files, assets, and data that are required to build one or more products. A target, however, refers to one of those products. A target contains the necessary instructions to build a product with the project's resources. This means that a project can contain multiple targets to build multiple products. As you can see, an Xcode project is more than just a folder with a bunch of files in it.
7. Build and Run: Take 1
Before we start modifying the source code of the project, it may be interesting to build and run your new project to see what the application template has given us for free. Click the Run button in the top left and make sure that the active scheme is configured to run the application in the iOS Simulator by selecting iPhone Retina (4-inch).
If all went well, the iOS Simulator should launch your application and display an empty, white view with the familiar status bar at the top.
8. Modify the User Interface
Let's get our hands dirty and modify the application's user interface. Open the Project Navigator and select the file named Main.storyboard. A file with a .storyboard extension is a user interface file. In this file, we create the user interface of the application.
The storyboard contains one item, a view controller with the white view you saw in the iOS Simulator a few moments ago. The workspace is composed of a sidebar showing the object representation of the scenes of the storyboard. The largest part of the workspace contains the scenes or the user interface of the application.
Select the object named View in the View Controller Scene in the left sidebar and see how the workspace and the right sidebar update their contents. A bunch of tabs appear at the top of the right sidebar. Each of the tabs contains a collection of attributes related to the object named View.
The lower half of the right sidebar contains a section with four tabs. The third tab is represented by an image of a three dimensional box. This box is how objects are commonly displayed in Xcode.
Click on the tab with the box icon and scroll through the list that appears. The list is referred to as the Object Library and contains various user interface elements, such as buttons, sliders, and switches.
At the start of this tutorial, I told you we were going to create an application with some user interactivity. The user should be able to touch the screen to change its color.
Detecting touches in an iOS application can be done several ways. One solution is to use a button. In the Object Library, find the item named UIButton
and drag it from the Object Library to the white view in Xcode's workspace.
The user should be able to touch any part of the screen, which means the button should cover the entire screen. Have you noticed the six, tiny squares at the button's edges? By moving the tiny squares, you can modify the button's dimensions.
Adjust the size of the button to make it cover the entire screen. Don't worry about the status bar at the top of the screen.
The view behind the button is the view that will change color when the user touches the screen. At the moment, the button is blocking the view from the user's view so we need to modify the button's attributes.
You may have noticed that the button has been added to the list of objects in the left sidebar, below the object named View. Select the button from the list of objects and select the Attributes Inspector in the right sidebar—the fourth tab from the left. We only need to make two adjustments.
Start by changing the type of the button from System to Custom. This will make the button transparent.
The second change we need to make is telling the user what to do by changing the button title. The text field next to the label Title currently reads Button. Change this to Tap to Change Color and set the Text Color to black so it's readable.
9. Add an Action to the View Controller
If you're familiar with the MVC (Model-View-Controller) pattern, then you have a head start learning iOS development. The MVC pattern is a pattern found in many languages and frameworks, such as Ruby on Rails and CodeIgniter.
The view in our user interface falls in the V category in the MVC pattern. A view is controlled by a controller. Take a look at the file names in the Project Navigator on the left. The files represent a view controller that control the view in our user interface.
What does a view controller do? A view controller can do whatever you want, but it's in the first place responsible for handling everything that happens in the view that it manages. This includes, for example, touches from the user. If the user touches the button in the view, it's the controller's responsibility to handle the touch event.
How do we handle a touch event? In the case of our button, we add an action to the view controller. An action is a fancy name for a method. What is a method? A method is at its core a C function. Wait. What? Don't worry about the terminology too much at this point. The next two posts will cover C and Objective-C in more detail. What you need to remember is that a method is like a method in Ruby and PHP, or a function in JavaScript.
If you invoke a method of a controller, it does something in response. In other words, if a user touches the button and we connect a method to that touch event, then the controller will do something in response to that touch event.
To add an action to the view controller that manages the view in our user interface, we need to make some changes to the file named TSPViewController.h. Files with a .h extension are header files. A view controller's header file contains information about the view controller—the view controller class, to be precise. We only need to add one line of code to the header file. Take a look at how I modified the view controller's header file.
// // TSPViewController.h // Colorific // // Created by Bart Jacobs on 27/03/14. // Copyright (c) 2014 Tuts+. All rights reserved. // #import <UIKit/UIKit.h> @interface TSPViewController : UIViewController - (IBAction)changeColor:(id)sender; @end
Even though we won't focus on the syntax in this tutorial, it's fairly easy to understand what's going on. The name of the action or method is changeColor:
and it has one argument, sender
. The type of the argument is id
, which means any object. What are objects again? Patience grasshopper. The action ends with a semicolon.
10. Implement the Action
We've added an action to the view controller, but the action doesn't do much. What we have done is declare an action. This simply means that any part of the application that takes a peak at the view controller's header file also knows that it has an action named changeColor:
. It's like a restaurant offering you the menu. You can see what it has to offer, but it doesn't show you what each item on the menu looks or tastes like.
What we need to do is implement the action and we do that in the view controller's implementation file. That's right. The file with the .m extension is the implementation file. Select the file named TSPViewController.m and have a look at its contents.
Did you expect it to be empty? Xcode has given us some boilerplate code that's common for view controllers. The nice thing about Objective-C is that it has very readable method names. Developers often complain that the method names are long, but the advantage is that you know what a method does just by looking at its name.
To implement the changeColor:
action, we copy what we wrote in the header file and replace the trailing semicolon with an opening and a closing curly brace.
// // TSPViewController.m // Colorific // // Created by Bart Jacobs on 27/03/14. // Copyright (c) 2014 Tuts+. All rights reserved. // #import "TSPViewController.h" @interface TSPViewController () @end @implementation TSPViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (IBAction)changeColor:(id)sender { } @end
I've added the contents of the entire implementation file so you can see where you should add the method implementation. It needs to be after @implementation TSPViewController
and before the last @end
. Also note that it cannot be nested in another method implementation.
It's time to do something useful in our action. I'm not going to explain each line of code in detail, but I'll give you the gist of what's happening.
- (IBAction)changeColor:(id)sender { int r = arc4random() % 255; int g = arc4random() % 255; int b = arc4random() % 255; UIColor *color = [UIColor colorWithRed:(r/255.0) green:(g/255.0) blue:(b/255.0) alpha:1.0]; [self.view setBackgroundColor:color]; }
As you may know, it's possible to break a color down into the three primary colors, red, green, and blue. In our action, we generate three random numbers between 0
and 255
, and use these numbers to create a random color.
The method we use to create the color is very descriptive, colorWithRed:green:blue:alpha:
. In the last line of our action, we set the background color of the view in our user interface to this new, randomly generated color.
The word self
refers to the view controller. Don't worry if none of this makes sense. It will become more clear once we've covered the basics of C and Objective-C in the next lessons.
Comments are important when writing code. Did you spot the comments I added to the implementation of changeColor:
? Single line comments start with two forward slashes (//
), whereas multiline comments start with /*
and end with */
.
11. Connect the Action
The method is implemented, but nothing spectacular will happen when we build and run the application. Give it a try if you don't believe me.
What's missing is a connection between the button and the view controller's action. How should the view controller know that the changeColor:
action needs to be triggered when the button is tapped?
Making this connection is simple. Open the storyboard by selecting the file named Main.storyboard and select the View Controller object in the View Controller Scene.
With the View Controller object selected, open the Connections Inspector in the right sidebar—the first tab from the right. If you've followed the steps correctly, you should see our new action in the section labeled Received Actions.
You should see an empty circle on the right of the changeColor:
action. Click and drag from the circle to the button in our user interface.
A menu will pop up when you release the mouse. The pop up menu contains a list of touch event types. The touch event that we're interested in is named Touch Up Inside. This event is triggered when a user touches the button and lifts her finger. This is the most common behavior of most buttons.
After connecting the button and the action, you should see that the right sidebar reflects the connection you just made. Great. You've successfully completed your first real application.
12. Build and Run: Take 2
Build and run your application in the iOS Simulator and start tapping the simulator's screen. Every time you tap the screen, its color should change to a new, random color. How cool is that?
Conclusion
We've covered a lot of ground in this tutorial. Even though this post was quite lengthy, we didn't actually do very much. If you know the theory, you can create Colorific in less than five minutes.
In the next two posts, I will cover the basics of C and Objective-C. This will prepare you for the interesting stuff in the rest of the series.
Comments