Understanding button press events

This is the “ButtonPress” example. I am going to show you the simplest way to press the button and change the event of button pressed.

Step 1: Open the Xcode and create a new Xcode project using View base application template. Give the application name “ButtonPress”. As shown in the figure below:

Step 2: Expand classes and notice Interface Builder created the ButtonPViewController.h and ButtonPViewController.m class for you. Expand Resources and notice the template generated a separate nib, ButtonPViewController.xib file.

Step 3: Open the ButtonPViewController.h file and add IBOutlet UILabel *statusText;
For displaying the Label Text, mention two IBAction. To perform the given actions make the following changes in the file.

#import <UIKit/UIKit.h>

@interface ButtonPViewController : UIViewController {
        IBOutlet UILabel *statusText;

}
@property (retain,nonatomic) UILabel *statusText;

(IBAction)buttonpressed:(id)sender;
(IBAction)buttonpressed1:(id)sender;
@end

Step 4: Double click the ButtonPAppViewController.xib file and after that make the following changes.
A) Open the view window, first drag the Round Rect Button from the library and place it to the view window and select the button.

B) Open the view window, and drag the Label from the library and place it to the view window.

Step 5: Open the ButtonPViewController.m file and make the following changes in the file.

#import "ButtonPViewController.h"

@implementation ButtonPViewController
@synthesize statusText;

(IBAction)buttonpressed:(id)sender
{
        NSString *newText =[[NSString alloc]initWithFormat:@"Right button pressed"];
        statusText.text=newText;
        [newText release];
}
(IBAction)buttonpressed1:(id)sender
{
        NSString *newText =[[NSString alloc]initWithFormat:@"Left button pressed"];
        statusText.text=newText;
        [newText release];
}

Step 6: Now build and run the code and view the Output in the Simulator.

You can download source code from here ButtonPress

Leave a Reply

Your email address will not be published. Required fields are marked *