27 May, 2011

iPhone Programming 101: How To Make a Tip Calculator

Written by

If you’re completely new to iPhone programming and want to dive right in, this is the tutorial for you!
In this tutorial, you’ll get started with iPhone programming by making a tip calculator!

Why make a tip calculator?  First, it’s one of the easiest exercises you can do, so it is a great way to get started with iPhone development.

Secondly, if you’re as slow at math as I am, it’s actually really handy sometimes and you may find yourself using it!  :]
So let’s get started, and get tipping!

Source Code Available here

Hello, iPhone!
To develop on the iPhone, you need a Mac.  Pretty much any Mac will do, whether a Mac laptop or what I used to get started – a Mac mini.
Once you have your Mac, you need to download and install Xcode 4, the program you’ll use to build your apps.  You can Download Xcode 4 from Apple’s site – it’s free if you’re a member of the iOS or Mac developer program, or you can buy it separately for a small fee if you’d like.
Once you have Xcode 4 installed, run it and go to File\New\New Project.  Choose iOS\Application\View-based Application, and click Next.

Tap for Larger

On the next page, enter TipCalculator for the Product Name.  For the Company Identifier put a unique string (such as one of your domain names, if you own one).  Make sure Device Family is set to iPhone, and click Next.

tap for larger

Finally, choose a folder to save your project in, and click Create.
Let’s see what you have so far!  In the toolbar at the top of Xcode, click Scheme and set it to your iPhone Simulator, as shown below:

Tap for larger

Then click the Run button in the upper left of the toolbar, and you should see your app run in the Xcode simulator!

Tap for larger

So far so good, except this is kinda boring!  Let’s make things a little more interesting by making the screen say “Hello, iPhone!”
In Xcode, you’ll see the files in your project listed off to the left.  Select TipCalculatorViewController, and it will bring up a visual editor for the main screen in your app:

Tap for larger

This visual editor is “Interface Builder” by the way, so I’ll refer to it by that from now on.
We want to add a label to this screen that reads “Hello, iPhone!”  But to do this, you need to bring up the window that shows you all the views and controls you can add to the screen.
To bring up this window, in the toolbar to the upper right, there is a segmented control with three buttons that reads View.  Click the button on the far right so it is shaded, and a window will slide in.
The window on the side is split into two parts – a top part and a bottom part.  On the bottom part, it also has a toolbar, that lets you look through various libraries of things to add.  Make sure the third tab item is selected, for the Object library.
Here’s a screenshot to show you the buttons you need to select:

Tap for larger

Now, from the library look for the item that reads “Label”, and drag it into the top middle of your view.  Double click the label and change the text to “Hello, iPhone!”

Tap for larger

Before we try this out, let’s make this text bigger, and a different color.  Make sure your label is selected, then in the top part of the sidebar to the right, select the fourth tab.
This will bring up attributes you can change on the label, such as the alignment, number of lines, etc.
You’ll seen an entry there for Font.  Click the button that looks like a T to the right of the font entry to bring up a visual editor, and set it to 36 points.
You’ll notice that after setting it, the label seems to stay the same size, but that’s just because you haven’t increased the size of the label itself yet, and by default it shrinks to the area you give to it.
So also increase the size of the label by dragging the blue dots at the edges until the text doesn’t grow anymore, and your screen should now look like this:

Tap for larger

One last step – let’s change the font color.  To do this simply click the black box next to Text Color to bring up the color editor, and pick your favorite color:

Tap for larger

And that’s it!  Click the Run button to run your project, and you should now have an App that says “Hello, iPhone!”

Tap for larger

Tip Calculator Layout
All the stuff you just did was to get you familiar with the basics of running iPhone apps and adding controls.
But that isn’t the way we want our Tip Calculator to actually look like, so let’s get the UI designed the way we’d like!
First, double-click the “Hello, iPhone!” label, and change the text to “Tip Calculator.”
Then, drag another label to the screen to the lower left of the “Tip Calculator” label, and change the text to “Bill Amount:”.

Tap for larger

Next, drag a Text Field from the library to the right of the label.  The Text Field is the control you use when you want the user to be able to enter numbers or letters.
Resize the Text Field a bit so it fits all the way to the edge of the screen as well.

Tap for larger

Now, repeat this process to add another label reading “Tip Percent:” and a text field to its right.
Also, drag a Round Rect button to the lower right, and double-click it to change the text to “Calculate!”
Finally, add a label right below the button that reads “Your tip should be: XXXX” and extend the size to fit the entire width of the screen.
At this point your layout should look as follows:

Tap for larger

Click the Run button to run your app in the Simulator, and you should see your layout appear.  Try tapping one of the text fields, and you’ll notice that the keyboard comes up, but there’s a problem: it defaults to letters!

tap for larger

The keyboard style is another example of something you can change in the attribute editor for a control.
So go select the two text fields (you can draw a border around them to select both), and change the keyboard to Numbers and Punctuation:

Tap for larger

Run your project again and tap on a text field, and now it’s easier to enter in a test tip amount!

Tap for larger

Of course, tapping the Calculate button does absolutely nothing, which is kind of disappointing!  So let’s take care of this next.

Views and View Controller: Overview
All of the things you’ve been adding to the Tip Calculator so far (labels, text fields, and a button) are called views.
If you think about it, somehow you’re going to need to write some code that has access to these views.
You’ll need to get the value of what the user put in for the bill amount and tip percentage, run a calculation on it, and put the result in the lable to the bottom.  You’ll also need to know when the button is clicked.
In iPhone development, the class that manages the views for a particular “screen” in your app is called a View Controller.  You may be familiar with this concept already if you’ve used the Model-View-Controller architecture in other languages.
Your project already has a TipCalculatorViewController class set up for you, in TipCalculatorViewController.h and TipCalculatorViewController.m.
So somehow, you need to find a way to hook up the views you’ve made in Interface Builder to this class!

Views and View Controllers: Hooking Up
To hook up the view controller to the views, we want to make an instance variable and property for each of the views we need to access in code, and a method that will be called when the button is tapped, as shown below:

Tap for larger

Luckily, this is incredibly easy in Xcode 4!
In the toolbar at the top of Xcode where it reads Editor make sure the second tab is selected to bring up the Assistant Editor.
Also, go to View\Assistant Layout\Assistant Editors on Bottom so it shows up below Interface Builder (I find it easier to work with that way).

Tap for larger

Make sure that the Assistant Editor is set up to Automatic in its toolbar, and that the TipCalculatorViewController is showing up in the editor.
Then, select the bill amount text field in Interface Builder, hold down control, and drag a line from it to right below the @interface block in the Assistant Editor:

tap for larger

A popup will appear.  Enter billAmountTextField for the name, and click Connect.
Once you’ve done this, you’ll see that it automatically creates an instance variable and property for you for billAmountTextField:

Tap for larger

If you control-click on the Text Field in Interface Builder, you’ll see that it has also associated the text field to the File’s Owner (which is TipCalculatorViewController).  This is the step that hooks up the code to the view, all done for you!

Tap for larger

Now repeat this process for the Tip Percentage text field (naming it tipPercentTextField) and the label at the very bottom (name it resultLabel).
Now we need to do something slightly different – hook up the calculate button to call a method in our view controller.  Luckily this is also quite easy with Xcode 4!
Drag a line from the Calculate button down to the assistant editor after the @interface as you did for the others, but this time change the Connection type from Outlet to Action.  For name, enter calcTapped, and click Connect.
This time, you’ll see that it’s created a method called calcTapped for you (that is empty right now).  Also if you control-click on the button in Interface Builder, you’ll see that it’s hooked up the Touch Up Inside event to this method for you.
Almost done!  In the Files & Groups tree to the left, select  TipCalculatorViewController.m to bring up the editor.  Scroll down to calcTapped, and replace the contents with the following:

- (IBAction)calcTapped:(id)sender {

NSString *billAmountString = [billAmountTextField text];

float billAmountFloat = [billAmountString floatValue];

NSString *tipPercentString = [tipPercentTextField text];

float tipPercentFloat = [tipPercentString floatValue];

float tipAmount = billAmountFloat * tipPercentFloat;

NSString *result = [NSString stringWithFormat:@"Your tip should be: %0.2f",

tipAmount];
    [resultLabel setText:result];
}
<span style="font-family: Georgia, 'Times New Roman', '<span class=;">Bitstream</span> Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">

The first thing this does is get the text the user entered for each field.  The UITextFields have a text property you can use to get this.

It needs to convert each of these values to floats so we can do the calculation.  Luckily NSString has a helper method called floatValue that will convert strings to floats.
Finally, it performs the calculation and sets the label to the result.
Click the Run button to run your project, and you should now have a functional Tip Calculator!

Tap for larger

Where To Go From Here?
Here is the sample project with all of the code from the above tutorial.
Contgratulations, you now have your very own iPhone app made from scratch, and pretty useful too!
But why not make it even better?  You could add another field where the user can enter the tax rate, so you’re not over-tipping!  Or you could try to pull the tip calculation code into a helper class (your Model) to keep the code a bit cleaner.

If you’re interested in learning more, check out the How To Make A Simple iPhone App Tutorial available on my iPhone Tutorial blog.  It shows you how to make an app about scary bugs, using some neat components in iPhone programming such as table views and image pickers!
I hope you enjoyed this tutorial, and best of luck in your iOS adventures!
This is a post by Ray Wenderlich, an indie iPhone developer passionate about making apps and teaching others the techniques to make them.  You can find more tutorials by Ray on his iPhone Tutorial blog.

Comments are closed.

%d bloggers like this: