Adding button and its handler in Objective-C using iPhone SDK


In JavaScript, it is fairly easy to add a button and its event handlers. HTML and the browser are your Interface Builder and your text editor is your Xcode. There is no need to graphically connect anything and there is no confusion where you add the button and where you add the event handlers. For iPhone programming, the model is more sophisticated and hence it is more complicated to nail the basics. So how do you add a simple button and its event handler in Objective-C and iPhone SDK?

Typically you will want to add a button using the Interface Builder and then add the button’s event handlers in Xcode. Here are the steps:

  1. In Xcode double click on the NIB file that defines the view to which you wish to add a button. This will start the Interface Builder (IB).
  2. In IB, open the Library tool and drag a button to the view. Position and resize this button and give it a title.
  3. Now you need to connect the button to the View Controller class so that you can control and customize this button from Xcode. You can control-click on the button and drag the connection line to the File’s Owner in the xib view (alternatively, you can start the IB’s Inspector, select the Button Connection tab and create a Referencing Outlet – drag the connection similar to before).
  4. In Xcode you’ll need to define the button to the view controller’s interface file and then define the methods to customize the button and define its events handlers.

In this sample, I’ve added a UILabel and a UIButton class so that when you click on the button the value of the label is changed.

@interface TestViewController : UIViewController {
	IBOutlet UILabel *mylabel;
	IBOutlet UIButton *mybutton;
}
@property (nonatomic, retain) UILabel *mylabel;
@property (nonatomic, retain) UIButton *mybutton;
@end

In the implementation file, you need “synthesize” the label and button objects.

@implementation TestViewController

@synthesize mylabel;
@synthesize mybutton;

Next I try to customize the label on the button and add an event handler.

- (void)viewDidLoad {
        [super viewDidLoad];
	mylabel.text = @"www.aquacue.com";
	[mybutton setTitle:@"Aquacue - Normal" forState: (UIControlState)UIControlStateNormal];
	[mybutton setTitle:@"Aquacue - Highlighted" forState: (UIControlState)UIControlStateHighlighted];
	[mybutton addTarget:self action:@selector(myButtonClick:) forControlEvents:(UIControlEvents)UIControlEventTouchDown];
}

Now here is the definition of the handler:

-  (void)myButtonClick:(id)sender {
	mylabel.text = @"Clicked";
}

Next I add another event handler so that when you click on the screen background, the value of the label is changed:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    mylabel.text = [NSString stringWithFormat: @"Hello Aquacue %@ %d", @"AAA", event.timestamp];
    [super touchesBegan:touches withEvent:event];
}

You can also use the IB to define event handlers (aka Actions). The easiest way is to actually define the handler/action in Xcode using the IBAction declaration in the interface file (add the declaration just before the @end statement).

- (IBAction)myButtonPressed:(id)sender;

Next you’ll need to define the myButtonPressed handler in the implementation file:

- (IBAction)myButtonPressed:(id)sender {
	mylabel.text = @"Change the label, when user clicks on the button";
}

Note that in this sample, I’ve defined two handlers one using the UIButton addTarget method and another using the IBAction. Both of these handlers are called when the user clicks on the button. As it turns it both of these handlers get called IBAction gets called first followed by the handler that was added via addTarget.

Only the methods defined with the IBAction declaration are exposed to the IB. You can control-click on the button object in IB and you’ll see a popup menu that defines all of the events that the object is willing to handle. Using the normal IB way, you’ll need to drag an event to the File’s Owner object to expose the event handler in Xcode.

19 Responses to “Adding button and its handler in Objective-C using iPhone SDK”

  1. elwood Says:

    Thanks for simple guide ! Is was very helpful.

  2. prakash Says:

    Hi

    Thanks for good tutorials….

    Really very helpful for me.

    Thanks & Regards
    Prakash Babu.K

  3. Rajeev Sharma Says:

    i have used this code in my application…….
    thanks for code.

  4. Ovidiu Says:

    Hello, I used this code, but I get a exception:

    Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘*** -[UIViewController myButtonPressed:]: unrecognized selector sent to instance 0x3f31740′

    ?!?!?

  5. ejaa Says:

    where is the statement to connect the button into next page?

  6. [TIP] iPhone SDK Tutorial - Adding a button and its handler Says:

    [...] This is a nifty iPhone development tutorial, that is quite helpful to developers new to iPhone: Adding button and its handler in Objective-C using iPhone SDK (the tutorial is a blog post on note19.com) Reply With Quote   + [...]

  7. masbog Says:

    i think if you added an image, your tutorial can viewing cool -___-”

  8. Stormy Says:

    Very very poorly written tutorial. Not clear where do you put all that code. I mean the very people who would need it – won’t be educated enough to guess which .h/.m file they have to edit and why.

  9. Rogier Festen Says:

    This tutorial helped me a lot. Thanks for writing.

  10. links for 2011-06-01 « Softwarebaer Says:

    [...] Adding button and its handler in Objective-C using iPhone SDK « n o t e 1 9 . c o m (tags: objective-c ios) [...]

  11. hardin Says:

    good one…..
    it’s help me lot to improve my skill.

  12. iPhone: addTarget Event in Button | aD@Y D3s!GN .com Says:

    [...] http://note19.com/2009/05/17/objective-c-adding-button-and-its-handler/ [...]

  13. College Textbooks Says:

    College Textbooks…

    [...]Adding button and its handler in Objective-C using iPhone SDK « n o t e 1 9 . c o m[...]…

  14. aniket Says:

    Excellent for beginners.

  15. lkjlkj Says:

    This helped allot

  16. Kisalay Says:

    Very good and useful tuts…tnxs for sharing it

  17. Patricia Says:

    Good little tutorial, but I have a question. When I drag from the button to the controller to create the IBAction method, must I also drag the button into the interface section to create a property?

    Thank you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: