X

Writing Calculator for iPhone iOS in Xcode

I believe, to learn any language with GUI capabilities one must take Calculator as an assignment. I’ve build that in FoxPro, VB 2.0, Oracle Power Objects, Java AWT, Swing and JavaScript. Now it is time to build the same for Apple iPhone using iOS Programming. What I am surprised to see is that this is really not challenging. It will not take much of your time to build Calculator to basic Level.

This calculator program is capable of taking input of any number with number buttons, Clear the screen, Perform Addition Subtraction, Multiplication and Division. No Negative numbers yet.

To keep it simple I’ve not gone into decimal calculations or scientific formulas. This code is written to learn the GUI capabilities of iOS and Xcode. There is lot of scope for improvement, but idea is to start very simple.

Step -1 : Start Xcode and create new project with Single view Application

Choose application to be deployed only on iPhone platform.

Step – 2: Go to storyboard and design the calculator using the Object Panel on right bottom.

  • Create  0 to 9 buttons, operations like add, subtract, multiply and divide. Also add the ‘C’ button to clear and ‘=’ button for actually doing total.
  • Create textfield object to show the numbers pressed.
  • Increase the font size to 30 point in attribute inspector to achieve same look as mine.

 

Step 3: Add the IBOutlets and IBActions in ViewController.h

  • CalcOperation enum is created to say these are the operations which will be supported by calculator and same will be used for storing the operation intended by user.
  • *display outlet is used for syncing with output textfield.
  • *cbutton is for clearing the textfield.
  • NSString *storage object is used for storing last operand in the memory when operator button is pressed.
  • operation variable is of enum type and one operation at a time will be stored here.
  • Other IBActions represent the method calls when the buttons are pressed.

 

//
//  ViewController.h
//  Test4
//
//  Created by Deepak Keswani on 14/02/12.
//  Copyright (c) 2012 deepakkeswani.com. All rights reserved.
//

#import 

typedef enum{ Plus,Minus,Multiply,Divide} CalcOperation;

@interface ViewController : UIViewController {
    IBOutlet UITextField *display;
    IBOutlet UIButton *cbutton;
    NSString *storage;
    CalcOperation operation;
}

- (IBAction) button1;
- (IBAction) button2;
- (IBAction) button3;
- (IBAction) button4;
- (IBAction) button5;
- (IBAction) button6;
- (IBAction) button7;
- (IBAction) button9;
- (IBAction) button0;
- (IBAction) plusbutton;
- (IBAction) equalsbutton;
- (IBAction) clearDisplay;

@end

 

 

Step 4: According to header declaration add the methods in ViewController.m file

You can add these methods above the viewDidLoad method.

- (IBAction) clearDisplay {
   display.text = @"";
}

- (IBAction) button1 {
    display.text=[NSString stringWithFormat:@"%@1",display.text];
}
- (IBAction) button2 {
    display.text=[NSString stringWithFormat:@"%@2",display.text];
}
- (IBAction) button3 {
    display.text=[NSString stringWithFormat:@"%@3",display.text];
}

- (IBAction) button4 {
    display.text=[NSString stringWithFormat:@"%@4",display.text];
}

- (IBAction) button5 {
    display.text=[NSString stringWithFormat:@"%@5",display.text];
}

- (IBAction) button6 {
    display.text=[NSString stringWithFormat:@"%@6",display.text];
}

- (IBAction) button7 {
    display.text=[NSString stringWithFormat:@"%@7",display.text];
}

- (IBAction) button8 {
    display.text=[NSString stringWithFormat:@"%@8",display.text];
}

- (IBAction) button9 {
    display.text=[NSString stringWithFormat:@"%@9",display.text];
}

- (IBAction) button0 {
    display.text=[NSString stringWithFormat:@"%@0",display.text];
}

- (IBAction) plusbutton {
    operation = Plus;
    storage = display.text;
    display.text=@"";
}

- (IBAction) minusbutton {
    operation = Minus;
    storage = display.text;
    display.text=@"";
}

- (IBAction) multiplybutton {
    operation = Multiply;
    storage = display.text;
    display.text=@"";
}

- (IBAction) dividebutton {
    operation = Divide;
    storage = display.text;
    display.text=@"";
}

- (IBAction) equalsbutton {
    NSString *val = display.text;
    switch(operation) {
        case Plus :
            display.text= [NSString stringWithFormat:@"%qi",[val longLongValue]+[storage longLongValue]];
            break;
        case Minus:
            display.text= [NSString stringWithFormat:@"%qi",[storage longLongValue]-[val longLongValue]];
            break;
        case Divide:
            display.text= [NSString stringWithFormat:@"%qi",[storage longLongValue]/[val longLongValue]];
            break;
        case Multiply:
            display.text= [NSString stringWithFormat:@"%qi",[val longLongValue]*[storage longLongValue]];
            break;
    }
}

Step 5: Create the connections between the display objects and methods.

  • Go to Storyboard view, click on ‘view controller’ from the ‘View Controller Scene’. Now click on ‘show the connection inspector’ in the right panel.
  • This will show the outlets and Received actions two subsection. Use the circle on right of each object to turn it into plus and drag and link with correct objects.
  • After linking your final screen should look like this.

Step 6: Build and Run the project to see the Calculator app in simulator.

If all goes well, you should be able to see calculator program running in iPhone Simulator.

Do let me know if you were able to perform the steps as mentioned in this post and what do you feel about this program.

If you wish you can also refer or download this code from here: https://github.com/deepakkeswani/SimpleCalculator

 

Deepak Keswani: Developing Applications for Computers since 1995 :)

View Comments (40)

  • Hi Deepak! Let me congratulate you for a well written article! Your website is a very nice initiative which will help many.

    I hope you don't mind if I put forward a suggestion. In this calculator app while a user is pressing a button you have written 9 methods for each number. Rather than doing that you could have just made a button, dropped the action on implmentation file and written this method.


    @property (nonatomic) BOOL numberBeingEntered;
    @synthesize numberBeingEntered=_numberBeingEntered;
    - (IBAction)digitPressed:(UIButton *)sender
    {
    NSString *digit=sender.currentTitle;//get the current title of the button pressed
    if(self.numberBeingEntered)//check if user is in the middle of entering a number
    {
    self.display.text=[self.display.text stringByAppendingString:digit];//append string with digit pressed
    } else {
    self.display.text=digit;//remove 0 in the display and add the digit pressed
    self.numberBeingEntered=YES; //now user has entered a number
    }
    }

    Once you have written this method, you can just copy the number 9 times and change the title to respective digits.

    • Thank you so much for adding this valuable comment. This is definitely concise & fast way of writing code.

      My idea of writing this code was to make it very very simple for beginners. I am sure people will enjoy upgrading my code with yours :)

  • Thanks a lot Deepak, for this very comprehensive tutorial, but how to implement a floating point.

    Thanks in advance, for eventually positive answer.

  • i am an early learner so....in starting i saw that with text and button you created with taking the outlet IBOutlet UITextField and UIButton ,whereas u created the button with taking 'action' in the coming lines so i just could nt understand
    thanks and plz do post

    • IBOutlets are created for setting and getting the values from the UI Objects in the code. We need to get and set the UITextField content.
      IBActions are created to capture the events from UI Objects and assign code block to them. We need to capture TouchUpInside Event on UIButton, thats why buttons are declared with IBAction.

  • Hello, thank you very much for the tutorial.

    However, I'm getting a parse issue, expected expression error in the following line:

    - (IBAction) clearDisplay {
    display.text = @"";
    }

    Any ideas why?

  • How can I get the display to show the whole equation, not just "number" then clear and "number" then clear and "Sum"?

  • Hi Deepak
    Thank you for this valuable tutorial
    When I tried to alter the code using property and synthesize for
    IBOutlet UITextField *display;
    IBOutlet UIButton *cbutton;
    NSString *storage;
    Rather than including them in the bracket
    I got a runtime exception...
    Is it a syntax issue?

  • i need an application which takes input from gui just like a mask and then crop the selected need help can you do it for me

    • It is just matter of setting the operands with positive or negative value.
      You can achieve that by multiplying operand with +1 or -1.

      • Hi deepak ..ur suggestion for code is good .can u give me small help for to have even first value when entering the second value in the display field.Can u suggest me the code how to implement it

Related Post