Back To Basics: Hello iPhone

    August 17th, 2011 Posted by: - posted under:Tutorials

    Today I’m going to show you how to make a simple “Hello World” project on the iPhone. There are quite a few ways that this can be accomplished, however I am going to show you the way that I feel will be the most beneficial.

    While I know many of iCodeBlog’s readers are veteran developers, this tutorial (and many in this series) are going to be geared towards the more novice developer. This group is often overlooked when it comes to tutorials, and my hope is to help lay a solid foundation for them (in addition to honing the skills of the veteran developers). So, let’s dig in.

    Introduction

    Generally, when you make a “Hello World” project, the goal is to get the text “Hello World” to display on the screen or the console. On the iPhone/iPad, there are quite a few ways to display text on the screen (labels, text areas, text views, core text, etc…). Today we are just going to focus on drawing the text using a UILabel.

    There are two ways to get a UILabel to display on the screen. The first is to use Apple’s Interface Builder tool. Interface Builder is an extremely handy tool for creating iOS interfaces visually. It supports drag and drop and allows you to configure all of the properties of each of the elements. While it is a great tool, I want to show you a bit what’s happening under the hood in code. It is important not to lean on Interface Builder as a crutch when creating interfaces as there are times when you will have to add UI elements manually. That being said, I will have an intro to Interface Builder tutorial up later in this series.

    Creating The Project

    Before we begin make sure you have read and understand the following tutorial:

    Back To Basics – Getting Set Up For iOS Development

    This tutorial will ensure that you have the proper environment set up for iOS development.

    When you first launch XCode, you are prompted with a screen similar to this one:

    To create a new project, simply click on Create a new XCode project. This will bring up a wizard guiding you through the initial project set up.

    Built into XCode are several different project templates to be used as a base for the most common projects that you might want to create. Each one comes with some specific “boiler plate” code to quickly get you up and running.

    We are going to start by clicking on View-based Application. This will give us enough code to have a simple view on the screen. A UIView is the simplest of display objects. Every other UI element that you draw on the screen will inherit from UIView. In the case of a view-based application, we are given a full screen blank view to start with. We can then add display objects as subviews.

    After selecting View-based Application, click next. This screen will show some simple project options such as name, company identifier, and Device family.

    Here’s a bit about each:

    • Name: This is simply the name of the application. Don’t worry you are not bound to this and you can easily change the display name.
    • Company Identifier This is unique id used to identify your application. It will be prepended to your project name to form the unique id that the app store uses. Identifiers are usually of the form com.companyName.projectName.
    • Device Family: This will be either iPhone or iPad. You can always upgrade to universal later (tutorial to come).

    The Files

    Once your project has been created, you will have 6 files of interest (for this tutorial’s sake):

    HelloiPhoneAppDelegate.h/m

    The app delegate is the point of entry for your application. It’s a singleton class (meaning there is only one), and it is responsible for displaying the main window/view of the application. You generally want to keep this class pretty lean and offload the work somewhere else. It’s often a n00b mistake to want to work on your UI/logic in the app delegate. For this project, we are not going to touch it at all. Just note that it is what’s launching your main view.

    MainWindow.xib

    Xib files are to be used with Interface Builders. They are basically xml files that Interface Builder uses to represent a user interface. In this case the MainWindow.xib (pronounced nib), is responsible for loading up our Window and Main ViewController (HelloiPhoneViewController). The View Controller could have been loaded programmatically in the App Delegate, however Apple has chosen to load in using a nib in Interface Builder for this template. I’m not going to go into detail about that in this tutorial, but you can see for yourself by opening up MainWindow.xib and look under objects.

    HelloiPhoneViewController

    iOS development tends to really enforce design patterns. This is basically the idea of separating the view code from the model code (using the controller code as the glue). Generally, in iOS when you have a view controller, it has a corresponding nib file(the view) to go along with it. HelloiPhoneViewcontroller.xib is where you would drag and drop UI elements to customize the view using the Interface Builder tool. As I mentioned in the beginning, we are going to ignore this file and add our text manually.

    The Code

    Well, this has been quite a bit of talk just to get us to the simple code below. Open up the file HelloiPhoneViewController.m and find the method called – (void) viewDidLoad . This method fires automatically when the view is first loaded. Make sure to uncomment it if it’s commented out. Inside of this method, add the following code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    - (void)viewDidLoad {
        [super viewDidLoad];
     
        CGRect frame = CGRectMake(10, 10, 300, 25);
        UILabel *helloLabel = [[UILabel alloc] initWithFrame:frame];
        helloLabel.text = @"Hello iPhone!";
        helloLabel.textColor = [UIColor blueColor];
        helloLabel.textAlignment = UITextAlignmentCenter;
        [self.view addSubview:helloLabel];
        [helloLabel release];
    }

    Let’s break down this code:

    Line 4: This creates a frame. Think of a frame as a box. The first two parameters are the starting x and y locations of the box, and the second two are the width and height of the box. Every display object you will create has a frame. It tells the device how big and where to draw a view.

    Line 5: On this line we create a new label object. The alloc says “give me the memory large enough for a UIlabel” and the init initializes all of the view properties. You will never really see these two methods called apart from each other. We call one of the copy constructors of UILabel called initWithFrame. This allows us to pass in the view’s frame on initialization.

    Lines 6-8: In these 3 lines, we configure various properties of a UILabel. The first is the actual text to be displayed, the second is the color of the text, and the third tells the text to center inside of it’s frame. There are quite a few options you can set with regards to any UI element and they can be found in the documentation for that particular object.

    Line 9: This is where we actually get the label to display. All views are subviews of some other view (even your main view is a subview of the window). We are basically attaching our label to the main view to be drawn. Without this line, your label would never be seen.

    Line 10: I don’t want to go too much into this right now, but The iOS platform (as of iOS versions < 5) doesn’t have garbage collection. What this means is, we need to handle our memory management ourselves. That being said, as a general rule, whenever you do an “alloc init” on an object, you must have a corresponding release call to give that memory back to the system. Otherwise, you have a memory leak. More to come on this.

    Running The Application

    OK, now that we have the code in place it’s time to run it in the simulator. To do this, select iPhone X.X Simulator in the dropdown at the very top of XCode (currently mine says 4.3). Then click the Run button. Your code will be compiled and the simulator will start. You should now see your _beautiful Interface_.

     

    Well, it’s not much to look at, but try reading the documentation and adding some other interface elements to the view. Or, read the documentation for UILabel and change some of the properties.

    If you have any questions or comments, feel free to leave them in the comments section of this post or send them to me on .

    You can download the source code for this tutorial here.

    Happy iCoding!

    This post is part of an iOS development series called Back To Basics. You can keep up with this series through the table of contents, RSS feed, or .