Thursday, November 26, 2009

Hello Xcode: add a button to do something

In this exercise, a button is used to trigger a event to happen, to do something.

Start Xcode, start a New Project. In this exercise, select Window-based Application, this template provides a starting point for any application. It provides just an application delegate and a window.



Name it HelloXcode and Save.

Double-click on the MainWindow.xib file to launch Interface Builder.

Drag a Label from Library to Window.


Now, we want to change some attributes. We have to open the Inspector Tool, click Tools from the top menu, and click Inspector.

Click the Label object on the Window pane, the Inspector pane will change to reflect your selection to edit Label attributes.

Make sure the first pane on the top of Inspector is clicked. Change some attributes, such as:
Change Text to Hello.
Change Layout to Center Alignment.
Front Size to 20
...


Next, add a Button, drag a Round Rect Button it from Library to Window. Double click on it, and type the text, Change.


We need a method in our code to do something, when the button is touched.

Now, go back to Xcode. Add the code in HelloXcodeAppDelegate.h

-(IBAction)buttonTouched;



Add the code in HelloXcodeAppDelegate.m

-(IBAction)buttonTouched{
UILabel *label = (UILabel*)[window viewWithTag:10];
label.text = @"Hello Xcode";
}



Switch back to Interface Builder, select the Label, and select the first pane on Inspector. Enter 10 on the Tag field.


Lastly, we need a connection between the button touch event to the method buttonTouched.

Click to select the button, click to select the second pane of Inspector, drag the circle beside Touch Down event to the Hello Xcode App Delegate object in the Document window.


When you release mouse, Interface Builder show you the available method can be connect, right now only one method available, select it.




Now you can Build and Go the application.