Saturday 7 February 2009

iPhone developer attaching events to buttons

Wahay all!

Right I have recently started developing for the iPhone and although the tools seem pretty robust and easy to use, working out how to start using them is a nightmare since the documentation seems to be seriously lacking. Just trying to do basic things like attaching an event to a button takes ages as I have to spend hours wading through the documentation to find the correct method parameters and all...

So here we go... I shall lay down my discoveries here as a reference for how to do the basic stuff, hopefully I can save people and myself some hassle in future.

So without further ado, lets rock and roll!!

To attach an event to a button.

Assuming you already have a .xib file with the button on it, and an associated view controller.

Declare the function in the view controller header file as (in italics)

@interface MainViewController : UIViewController {

    NSMutableData *receivedData;

}



- (IBAction)startScan:(id)sender;


I've called my event handler startScan. You should call it something else, depending on what your event will do. Mine started a scan...

The IBAction bit identifies this function as one that will show up in interface builder so we can attach this method to the button.

Then define the method in the .m file as


- (IBAction)startScan:(id)sender 

{

}


Now get funky.

Double click on the view.xib file to open up the interface in interface builder. Add your button onto the Main View. Right click on the File's Owner icon. You should see your defined method under Received Actions. To the right of the method name there is a little circle. If you click on this a + symbol appears in the circle. Drag this onto the button. Up will pop a list of possible events to attach to the method. Normally you would choose "Touch Up Inside". Wahay! 

Now all you gotta do is write some code to do something groovy inside your event handler and you are away!

Go forth and groove and let your hearts be your guides.




No comments:

Post a Comment