Monday, June 25, 2012

Getting Started with iOS.

This is a "Hello World" tutorial to iOS programming.  We are going to build an iPhone app that has a counter and two buttons.  Tapping the "+1" button increments the counter and tapping "-1" decrements the counter.

Open Xcode and start a new project File->New->Project.  Under iOS templates select Application and then "Single View Application"

Click on "Next" and choose the options for the project.  Type in "Counter" for Product Name and Class Prefix.  Company Identifier can be anything, so put your company name or n/a.  Select iPhone for Device Family and make sure that "Use Storyboards" and "Use Automatic Reference Counting" checkboxes are selected.

Click Next to save your new project.  Xcode should have created 5 different files for you:
1) CounterAppDelegate.h
2) CounterAppDelegate.m
3) MainStoryboard.storyboard
4) CounterViewController.h
5) CounterViewController.m

We will make changes to the the last 3 files in this project.

Open MainStoryboard.storyboard.

In the lower right corner is the Object Library.  From the Object Library drag two "Round Rect Buttons" and a "Label" to the canvas.  Double click on the buttons and on the label and change their titles to the following.

Now we need to create outlets and actions to connect our buttons to the code.  There are a few different ways to create actions and outlets in Xcode.  The easiest one is to click on the assistance editor button

This will open CounterViewController.h to the right of the storyboard.  Click ctrl and drag from each button to the area between @property and @end in the CounterViewController.h file.  A pop up will appear, select Connection=action and set Name=decrement for the "-1" button and Name=increment for "+1" button.  Press Connect to create the action.

Do the same for the label but set Connection=outlet and Name=label.  We also need to add a counter to keep track of our value.  Again in CounterViewController.h under @interface add the following code "@property (nonatomic) int counter;"  After adding all this CounterViewController.h should look like similar to this.

We need to synthesize the counter variable, open CounterViewController.m and under "@synthesize label" type "@synthesize counter";

Find "- (IBAction)decrement:(id)sender" and "- (IBAction)increment:(id)sender" in CounterViewController.m and add the following code.

The app is ready to run.  Go to Product->Run and wait for the sumulator to load. Every time you press +1 button the number in the label increases by 1, pressing -1 button decreases the counter by 1.

I recommend getting the iOS Programming:The Big Nerd Ranch Guide (3rd Edition) book for learning iOS in more depth. 

Please support this blog by making your next Amazon purchase from this link or consider donating in bitcoins:

No comments:

Post a Comment