Monday, January 2, 2012

iPhone Button Example


Make sure you have : Installed iPhone sdk with Xcode
while i am using iOS sdk 5.0 with IDE Xcode 4.1

So here we go... start with new project in Xcode

 and select as a "Single View Application" 

Put the some text
Project Name : ButtonView
Package : com.rdc 
Device Name : iPhone

we will get this..

so let's begin development..
Click on the xib file then click show/Hide utility tab to show the Utility on Top-right side in Xcode, drag one Label and Button on View then set the name of Button "Click Me" as shown in snap shot
After that click on  show/hide tab to Hide utility

now we need to create an instance of Button and an Action Method for button click action in "ButtonViewViewController.h" file :
to create an instance of Button click on Editor tab add {....} after
@interface ButtonViewViewController{
.......drag here to define outlet (instance) for button......
}
and right click on button then drag from (+) "new referencing outlet option"

we will get this small window so put the name like "btn" and click on Connect..
now do same for Label and put name "lbl" and Connect!!

to create an Action Method for button click drag from (+) "Touch Up Inside" option


we will get this small window so put the name like "btnClicked" and click on Connect..

finally we have code in "ButtonViewViewController.h" file like this..

#import <UIKit/UIKit.h>
@interface ButtonViewViewController : UIViewController{

IBOutlet UIButton *btn;
IBOutlet UILabel *lbl;
}

-( IBAction ) btnClicked: (id) sender;
@end

after this, complete header file ( "ButtonViewViewController.h" file) will look like this..

Now click on the left most button "standard editor" like this..
open "ButtonViewViewController.m" file
you will see that it showing error in "viewDidUnload" method on release
so make it comment... why click here
now scroll down you will get method "btnClicked" here so add some code in this
-( IBAction ) btnClicked: ( id ) sender {
     lbl.text = @"Button has been clicked..";

after this, complete implementation file ( "ButtonViewViewController.m" file) will look like this..

okay that's it!! we have done!! save it (press windows/command button + S)

Now Run Project like this way..

you will get output like this snap shot when you click on button..

Great we have done good job now we should go for some snacks  :)
I'd love to hear your thoughts!!