How To Handle Basic Interaction In iPhone?

We are going to write a slightly more complex application, one with two as well as a label. When the user taps either of the buttons, the label’s text changes. This may seem like a rather simplistic example,but it demonstrates the key concepts you will need to master the use of controls in your iphone application.

Step 1:  Create a View base application using template. Give the application name ”Button Fun”.

Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the directory structure to check out the content of the directory.

Step 3: Expand classes and notice Interface Builder created the Button Fun class for you. Expand Resources and notice the template generated a separate nib, Button_FunViewController.xib, for the “Button Fun”.

Step 4: In the Button_FunViewController.h file, we have created instance of UILabel class and define two IBAction: method. So make the following changes in the file.


#import <uikit/UIKit.h>

@interface Button_FunViewController : UIViewController {
IBOutlet UILabel *statusText;

@property (retain, nonatomic) UILabel *statusText;




Step 5: Double click .xib file. The nib file should open in Interface Builder. Drag a label from the library over to the view window and place at buttom of the view. Click it to select and bring up the inspector. Change the text alignment to centered by using the text alignment buttons.Double click the label and delete the existing text. Next we are going to draw two Round Rect Buttons from library to our view. Double click the button on the Left, and change its text to read “Left”, and double click the button on the right, and change its text to read “Right”. (See Figure 1)

Figure 1: The Finished view.

Step 6: Now we control-dragged from File’s Owner to the label object and selected status Text. Single click the Left button and bring up connection inspector. Drag Touch Up Inside to File’s Owner icon and select buttonPressed: action. Do it once again with Right button and select buttonPressed1: action. Save it and go back to Xcode.

Step 7: Open the Button_FunViewController.m file and make the following changes in the file.


NSString *newText = [[NSString alloc] initWithFormat:
@" Left Button pressed"];
statusText.text = newText;
[newText release];

NSString *newText = [[NSString alloc] initWithFormat:
@" Right Button pressed"];
statusText.text = newText;
[newText release];



Step 8: Now compile and run the application in the Simulator. (See Figure 2)

Figure 2: The simple two button application.

You can downloaded SourceCode from here Button Fun

Leave a Comment:

1 comment
Brian McCarthy says September 27, 2010

As a student new to Edu I found this example excellent. Worked first time when I hand coded myself. Thank you Sushant for the course

Add Your Reply