Quantcast
Channel: Envato Tuts+ Code - Mobile Development
Viewing all articles
Browse latest Browse all 1836

Creating Your First iOS Application

$
0
0

Even though we have already learned quite a bit in this series on iOS development, I am sure you are eager to start building iOS applications that do something cool or useful. In this tutorial, your wish will be granted! Using Xcode, you will 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 are about to build. The idea behind Colorific is simple. Every time the user touches the screen of the device, the color of the screen will change. Even though the concept is basic, Colorific is perfect for getting started and exploring the ins and outs of iOS development.


Step 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 opening Xcode’s File menu. Select New from the list of options and choose Project… (figure 1). An alternative option is pressing Shift + Command + N.

In case Xcode’s welcome window pops up when you launch Xcode, I advise to close it so you learn how to create a new project using the Xcode menu.

Creating Your First iOS Application - Creating a New Xcode Project - Figure 1

Step 2: Choose an Application Template

Getting started with a new application or project is easy in Xcode thanks to the application templates that ship with it. For the application that we are about to create, we need the Single View Application template (figure 2). Feel free to take a look at the other application templates, but make sure to choose the Single View Application template for Colorific.

Creating Your First iOS Application - Chooosing an Application Template - Figure 2

Step 3: Configure the Project

After selecting the Single View Application template and clicking the Next button, Xcode presents you with a list of options that allows you to configure your new project (figure 3). Let’s take a look at the various options.

Creating Your First iOS Application - Configuring the Xcode Project - Figure 3
  • Product Name: The product name will be the name of your application. I have named our application Colorific, but feel free to name your application whatever you would 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 copyright notices 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.
  • Bundle Identifier: Even though you cannot specify the bundle identifier when creating a new Xcode project, you can change it once you have 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 musn’t contain whitespace.
  • Class Prefix: When creating custom classes in your project, it is 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.
  • Devices: In the current version of Xcode (4.5 at the time of writing), the devices drop down menu contains three options, (1) iPad, (2) iPhone, and (3) 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.
  • Use Storyboards: Check this option if you plan to use storyboards in your project. To not overcomplicate our project, we will not be using Storyboards.
  • Use Automatic Reference Counting: If you are new to iOS development, then I strongly recommend that you use automatic reference counting (ARC) in your project. Automatic reference counting became available with the introduction of iOS 5 in 2011. It rids developers of having to manage memory manually. Prior to iOS 5, developers had to manually keep track of objects and memory. Don’t worry about ARC and memory management for now. I will explain these topics in more detail at a later point in this series.
  • Include Unit Tests: Testing is a key component of iOS development. As with storyboards, I don’t want to overwhelm you too much right now, so we won’t be using unit testing in this project.

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 figure 3. Note that most options can easily be changed after you have created your project. Click the Next button when you are finished configuring your project.


Step 4: Save the Project

In the next step, Xcode asks where you want to save your new project (figure 4). You may have noticed the little checkbox at the bottom of the window labeled Create a local git repository for this project. 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 are 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 iOS (and OS X) community. It is perfectly possible to use a different SCM system, such as SVN or Mercurial, if you prefer.

Creating Your First iOS Application - Save Your New Project - Figure 4

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.


Step 5: Exploring Xcode’s User Interface

Before we move on, I want to take a few minutes to explore Xcode’s user interface (figure 5). You can see four distinct areas, (1) a toolbar at the top, (2) a sidebar on the left, (3) a main view in the center, (4) and a sidebar at the right. Let’s briefly explore each area.

Creating Your First iOS Application - The Default User Interface of Xcode - Figure 5

Toolbar

The toolbar at the top contains the buttons and menus that you will find yourself using often (figure 6). 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 button on the far right brings up Xcode’s Organizer. 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.

Creating Your First iOS Application - Xcode's Toolbar - Figure 6

Navigator

The main purpose of the left sidebar is for navigation and it is often referred to as Xcode’s navigator (figure 7). It has different tabs with the Project Navigator at the far left. The selection in the left sidebar determines what is show in Xcode’s main view.

Creating Your First iOS Application - Left Sidebar or Navigator - Figure 7

Main View

The main view is the area where you will spend most of your time (figure 8). It is the Xcode’s workhorse and displays whatever is selected in the navigator.

Creating Your First iOS Application - Xcode's Main View - Figure 8

Inspector

While the the left sidebar controls what is being displayed in Xcode’s main view, the contents of the right sidebar reflect what is being displayed or selected in the main view (figure 9). The right sidebar, also known as the inspector, adapts itself to whatever the user selects in the main view.

Creating Your First iOS Application - Xcode's Main View - Figure 9

Step 6: Exploring the Project

It is time to take a look at the project itself. The project’s contents are displayed in the Project Navigator, the first tab of the left sidebar. Select the first item in the Project Navigator to see the project details in the main view (figure 10).

Creating Your First iOS Application - Xcode's Main View Showing the Project's Details - Figure 10

The main view is composed of two sections, (1) a sidebar on the left and (2) a detail view on the right. In the sidebar, you see two items, (1) your project with one item and (2) targets with one item. It is 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.


Step 7: Build and Run: Take 1

Before we start modifying the source code of the project, it is 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 6.0 Simulator.

If all went well, the iOS Simulator should launch your application and display a gray view.

Creating Your First iOS Application - Build and Run: Take 1 - Figure 11

Step 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 MTViewController.xib. A file with a .xib extension is a user interface file and can be edited with Xcode’s Interface Builder hence the last two letters of the .xib extension.

Creating Your First iOS Application - The Application's User Interface - Figure 12

After selecting MTViewController.xib, you should see the gray screen you saw a few moments ago in the iOS Simulator. The main view is composed of a sidebar showing a section labeled Placeholders and a section labeled Objects (figure 12). The largest part of the main view contains the user interface. Select the object named View in the sidebar and see how the right sidebar updates its 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 (figure 12).

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 (figure 13). 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 (figure 13).

Creating Your First iOS Application - The Object Library - Figure 13

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. The second item in the Objects Library is the button that we need. Click and drag a Round Rect Button from the Object Library to the gray view in Xcode’s main view.

Creating Your First iOS Application - Drag a Button from the Object Library to the Main View - Figure 14

The user should be able to touch any part of the screen, which means that the button should cover the entire screen. Have you noticed the six, tiny squares at the button’s edges? By dragging the tiny squares, you can modify the button’s dimensions (figure 15). Adjust the size of the button to make it cover the entire screen (figure 16). Don’t worry about the black status bar at the top of the screen. The status bar shouldn’t be covered by the button.

Creating Your First iOS Application - Resize the Button to Cover the Entire View - Figure 15
Creating Your First iOS Application - The Button Covers the Entire view - Figure 16

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 slightly 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 (fourth tab from the left). We only need to make two simple tweaks.

Start by changing the type of the button from Rounded Rect to Custom (figure 17). This will make the button transparent and remove its rounded corners.

Creating Your First iOS Application - Modify the Button Type - Figure 17

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 something like Tap to Change Color.

Creating Your First iOS Application - Modify the Button Title - Figure 18

Step 9: Add an Action to the View Controller

If you are 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 is 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 is 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 will do 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 MTViewController.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.

//
//  MTViewController.h
//  Colorific
//
//  Created by Bart Jacobs on 04/12/12.
//  Copyright (c) 2012 Mobile Tuts. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface MTViewController : UIViewController
- (IBAction)changeColor:(id)sender;
@end

Even though we won’t focus on the syntax in this tutorial, it is fairly easy to understand what is 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.


Step 9: Implement the Action

We have 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 is like a restaurant that offers you a 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 is right. The file with the .m extension is the implementation file. Select the file named MTViewController.m and have a look at its contents.

Did you expect it to be empty? Xcode has given us some boilerplate code that is 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 the 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.

//
//  MTViewController.m
//  Colorific
//
//  Created by Bart Jacobs on 04/12/12.
//
#import "MTViewController.h"
@interface MTViewController ()
@end
@implementation MTViewController
- (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 have posted the contents of the complete implementation file so you can see where you should add the method implementation. It needs to be after @implementation MTViewController and before the last @end. Also note that it cannot be nested in another method implementation.

It is time to do something useful in our action. I am not going to explain each line of code in detail, but I will give you the gist of what is happening. As you may know, it is 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. Again, 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 have covered the basics of C and Objective-C.

- (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];
}

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 */.


Step 10: Connecting 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 is 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 view controller’s xib file by selecting the file named MTViewController.xib. In the main view’s sidebar (on the left), select the object named File’s Owner in the section named Placeholders. As the name somewhat implies, the File’s owner is the object that owns the objects in the user interface file, including the view in which the button resides.

With the File’s Owner object selected, open the Connections Inspector in the right sidebar (first tab from the right). If you have followed the steps correctly, you should see our new action in the section labeled Received Actions (figure 19). 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 (figure 19). A menu will pop up when you stop release the mouse (figure 20). The pop up menu contains a list of touch event types. The touch event that we are 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.

Creating Your First iOS Application - Making the Connection: Part 1 - Figure 19
Creating Your First iOS Application - Making the Connection: Part 2 - Figure 20

After connecting the button and the action, you should see that the right sidebar reflects the connection you just made (figure 20). Great. You have successfully completed your first (real) application!

Creating Your First iOS Application - The Connection is Made - Figure 21

Step 11: 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 have 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.


Viewing all articles
Browse latest Browse all 1836

Trending Articles