iPhone & iPad Tutorial: Working With Buttons


Lesson 4:

Let’s go the next step after our little ‘hello world’ demonstration of coding for the iPhone/iPad. In this tutorial, we are going to provide an example of the M-V-C (Model, View, Controller) process of creating an app for the iPhone or the iPad.

Model
To get started we need to create our model.  This translates into creating the header and main file of the program code.  Our project is just a simple app with two buttons.  When you click on the left one, ‘Left button pressed’ will appear in a label. When you click on the right button, ‘Right button pressed’ will appear in the same label.  Nothing overly challenging, but it will give us the opportunity to practice the MVC.

The code for the header file is:

After @interface type:

UILabel  *myText;
}

@property(retain, nonatomic) IBOutlet UILabel *myText;

-(IBAction)buttonPressed:(id)sender;

In the main file:

@synthesize myText;

-(IBAction)buttonPressed:(id)sender
{
NSString *title = [ sender titleForState:UIControlStateNormal];
NSString *newText = [[NSString alloc] initWithFormat: @”%@ button pressed.”, title];
myText.text = newText;
[newText release];
}

Add
[myText release];

before
[super dealloc]

[tubepress video=”lnrSZg_5a_w”]

View and Controller
The view and controller are easy to configure.   This short video should demonstrate how to do it effectively:

[tubepress video=”3ehRE_IVfks”]

Return to iPhone Course

Recent Posts