IPhone SDK HelloWorld

Getting started developing on the IPhone SDK

This is a tutorial for beginners to the IPhone SDK and includes instructions on creating a basic HelloWorld program. The program demonstrates the use of Views, Labels and UIButtons. I will be using the 2.0 SDK so some features may not be available in the earlier version.


Step 1: Download XCode and the SDK


The first thing we need to do is to download the development tools namely XCode and the SDK. To download either of these you will need to register for the Apple ID and Apple developer Connection (ADC). Install both these tools, the procedure to do so is fairly trivial so I am not going into details.
 

Step 2: Create a new Project

Now we have the tools we need to start coding but before we do we need to create a new project. Select File > New Project or Apple Key + Shift + N to bring up the new project menu. Select the Applications item of the IPhone OS section from the menu on the left, and select View Based Application from the icons on the right. When prompted enter a project name, I have used HelloWorld in the sample code.


When you create a project you will see a window similar to the one shown in the image on the right. There are four files in the Classes package;
HelloWorldAppDelegate.h
HelloWorldAppDelegate.m
HelloWorldViewController.h
HelloWorldViewController.m  

We do not need to change the HelloWorldAppDelegate but just for information I would like to highlight some important parts of the auto-generated code.
The delegate header file contains a reference to a UIWindow object (Line 14) which controls all the user interaction for this application and will manage all other interface components. It also contains a reference to HelloWorldViewController (Line 15) which we will see later manages our one sample view.  

In the source file for the application delegate (HelloWorldAppDelegate.m) we find an auto generated applicationDidFinishLaunching method. This, as the name suggests, invoked when the application has been loaded and in this method we will add our HelloWorldViewController object to the UIWindow and make it visible;
 
22    [window addSubview:viewController.view];
23    [window makeKeyAndVisible]; 

The IPhone SDK UI follows the Model View Controller (MVC) design pattern and hence each view  has a corrsponding View Controller Object. XCode has automatically created a view for us, (its defined in the HelloWorldViewController.xib file you can see it by double clicking it in the side menu) and linked it to HelloWorldViewController. We now need to add controls to the view handle the generated events. Note we can add controls via a GUI interface called the Interface Builder but I am using the programmatic way for this tutorial.

Step 3: Adding Controls and Handler to header file


Open the HelloWorldViewController.h file and within the curly braces delinting the HelloWorldViewController interface declaration add the following lines;

IBOutlet UIButton *button;
IBOutlet UILabel *label;
IBOutlet UIView *myView;


We are defining a view to display and a button and label to go in the view. After the curly braces add a method declaration to accept the click event of the button and also properties to access the  UI elements; myButton, myLabel and myView. Your entire code should look something like this:

1    #import <UIKit/UIKit.h>
2
3    @interface MyHelloWorldViewController : UIViewController
4    {
5
6        IBOutlet UIButton *button;
7        IBOutlet UILabel *label;
8        IBOutlet UIView *myView;
9    }
10
11    -(IBAction)handleEvent:(id)sender;
12    @property (nonatomic, retain) UIButton *button;
13    @property (nonatomic, retain) UILabel *label;
15    @property (nonatomic, retain) UIView *myView;
16
17    @end

Step 4: Adding Controls


First add a synthesize the three UI elements to create the getter and setters. Add the following two lines of code after the @implementation HelloWorldViewController command in line 11 of HelloWorldViewController.m file.

@synthesize button;
@synthesize label;
@synthesize myView;

Now find the comment saying "Implement loadView if you want to create a view hierarchy programmatically." and un-comment the loadView method that follows this line. Add the following lines to the method to create a button and label;
1    - (void)loadView
2    {
3    // create and configure the view
4    CGRect cgRct = CGRectMake(0.0, 0.0, 480, 320); //define size and position of view
5    myView = [[UIView alloc] initWithFrame:cgRct]; //initialize the view   
6    myView.autoresizesSubviews = YES;              //allow it to tweak size of elements in view
7    self.view = myView;       

8    
// create a UIButton (UIButtonTypeRoundedRect) and play arround with settings
9    button = [UIButton buttonWithType:UIButtonTypeRoundedRect];   
10   button.frame = CGRectMake(100, 100, 100, 50); // size and position of button
11   [button setTitle:@"Add" forState:UIControlStateNormal];
12  button.backgroundColor = [UIColor clearColor];
13  button.adjustsImageWhenHighlighted = YES;    

14 
//Add action handler and set current class as target
15  [button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];

16  //Display Button
17  [self.view addSubview:button];
       
18  //create a label
19  cgRct = CGRectMake(100, 170, 100, 50); //define size and position of label
20  label = [[UILabel alloc] initWithFrame:cgRct];
21  label.text = @"Hello World";

22  //Display Label
23  [self.view addSubview:label];
24  }


Click the Build and Go button to check your interface is drawn correctly It should look something like to screen shot below.
 

Step 5: Handling Actions



We have already told the button to send an event (action) to the current class (self) in case of an UIControlEventTouchUpInside event but there is no handler defined to accept the event. We define a handler method in the class by adding the method shown below. It is doing two things, changing the text property of the label and adding a message to the log file. 
 
1    -(void)action:(id)sender
2    {
3        NSLog(@"UIButton was clicked");
4        label.text = @"Bye World";
5    }


Now click the Build and Go button again and click the button. The text of the label should change.


Concluding Note


This document is a bit raw please leave feedback in case anything is not clear or if you spot any mistakes.

You can find the source code of the example at my website;
Source Code

Comments

Code convention

Hi, your example helps. I tried to create button with 'initWithFrame' and stuck.
I have a question. Isn't this a bad style to send 'retain' straight after convenience 'buttonWithType' method creation? Instead of 'self.button = [ UIButton buttonWithType...]';

Last edited Apr 20, 2009 4:20 AM
Report abusive comment

Good work

Hi
Good tutorial - code works perfectly. Most of it makes sense. Since this is for the beginners, it would be helpful if you could explain important parts of the code too. Like what does this mean and what are its other uses - forControlEvents:UIControlEventTouchUpInside. Or maybe just refer people to the right API to look up.
Thanks a lot though :)

Last edited Mar 29, 2009 6:22 PM
Report abusive comment

Query on creating multiple view

Hi dear,
I am working on a application where I am creating multiple views
and on a click of button in first view the second view is loaded.
I know how to generate click event for a button,I have written loadView function for second screen like the above function. I am not able to call this function on click of button in first view.Second query is should I create a view from nib for second screen can I workout with first view replacing its controls with controls of second ?

Last edited Oct 3, 2008 7:12 PM
Report abusive comment

Untitled

Nice tutorial, well documented!

There is one minor error, you mention to add the following at step 3:
IBOutlet UIButton *myButton;
IBOutlet UILabel *myLabel;
IBOutlet UIView *myView;

Actually the 'my' in myButton and myLabel should disappear. The source below the mentioned lines displays the correct code:
6 IBOutlet UIButton *button;
7 IBOutlet UILabel *label;
8 IBOutlet UIView *myView;


But altogether, I like the the tutorial, thanks!

Last edited Sep 10, 2008 12:49 AM
Report abusive comment
Moderated collaboration
All signed in users can suggest edits to the knol, but these need approval from an author before being published
Version: 36
Versions
Last edited: Apr 19, 2009 2:28 PM.

Activity for this knol

This week:

195pageviews

Totals:

35629pageviews
9comments