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.

Developing Calculator Program in iOS

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

Choose application to be deployed only on iPhone platform.

Create new Xcode Project, Single View

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.

Calculator design in Xcode Storyboard

 

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

 



About Deepak Keswani 98 Articles
Developing Applications for Computers since 1995 :)

40 Comments

  1. 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.

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

    Thanks in advance, for eventually positive answer.

  3. 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.

  4. 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?

  5. How can I get the display to show the whole equation, not just “number” then clear and “number” then clear and “Sum”?

  6. 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?

      • 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

  7. Hi, I was wondering why do you only need to have -(IBAction) plusbotton in the header file but not for the other operations?  Thanks in advance for any comment.

    • You caught me 🙂
      Well, Ideally as a good practise, you should have all the declarations in the header. But even methods directly added to implementation can be invoked from interface builder objects. So code works, but as a good practise you should have all declarations in header.

  8. hi , thanks for the simple way .

    i got a question maybe u can help me with , how can i Calculate  a textfield in a loop or in an array programmatically ?

    i got a textfield in a loop and i wnat to Calculate the input in another textfield  .

    x = 36;     y = 0;   w = 36      h = 25 ;

    moretext = 0 ;

    for (moretext=0; moretext<5; moretext ++) {

    textFiled1 = [[UITextField alloc]initWithFrame:CGRectMake(x, y, w, h)];

    textFiled1.textAlignment = NSTextAlignmentCenter;

    textFiled1.backgroundColor = [UIColor clearColor];

    textFiled1.font = [UIFont fontWithName:@”Helvetica ” size:(8)];

    x+=36 ;

    [self.view addSubview:textFiled1];

    }

    i want to have the TOTAL for the textfield1 input showing in textfield2

     

    textFiled2 = [[UITextField alloc]initWithFrame:CGRectMake(180, 0, 36, 25)];

    textFiled2.textAlignment = NSTextAlignmentCenter;

    textFiled2.backgroundColor = [UIColor clearColor];

    textFiled2.font = [UIFont fontWithName:@”Helvetica ” size:(8)];

    [self.view addSubview:textFiled2];

    i dont know how to get the sum for a textfield in a loop or an array

  9. For all other functions.. i guess this is usable

    – (double) performOperation:(NSString *)operation: (double)value{
    double result = 0.0;
    if([operation isEqualToString:@”√x”]){
    result = sqrtf(value);
    }else if([operation isEqualToString:@”+ / -“] && value != 0.0){
    result = -1 * value;
    }else if([operation isEqualToString:@”1/x”] && value != 0.0){
    result = 1.0 / value;
    }else if([operation isEqualToString:@”x²”] && value != 0.0){
    result = pow(value,2);
    }else if([operation isEqualToString:@”log”] && value != 0.0){
    result = log10(value);
    }else if([operation isEqualToString:@”ln”] && value != 0.0){
    result = log(value);
    }else if([operation isEqualToString:@”sineD”]){
    result = sin((value * M_PI) / 180);
    }else if([operation isEqualToString:@”sineR”]){
    result = sin(value);
    }else if([operation isEqualToString:@”cosD”]){
    result = cos((value * M_PI) / 180);
    }else if([operation isEqualToString:@”cosR”]){
    result = cos(value);
    }else if([operation isEqualToString:@”tanD”]){
    result = tan((value * M_PI) / 180);
    }else if([operation isEqualToString:@”tanR”]){
    result = tan(value);
    }else if([operation isEqualToString:@”asineD”]){
    result = asin((value * M_PI) / 180);
    }else if([operation isEqualToString:@”asineR”]){
    result = asin((value * 180) / M_PI);
    }else if([operation isEqualToString:@”acosD”]){
    result = acos((value * M_PI) / 180);
    }else if([operation isEqualToString:@”acosR”]){
    result = acos((value * 180) / M_PI);
    }else if([operation isEqualToString:@”atanD”]){
    result = atan((value * M_PI) / 180);
    }else if([operation isEqualToString:@”atanR”]){
    result = atan((value * 180) / M_PI);
    }
    return result;
    }

  10. How about this..  for cos tan etc

    – (IBAction)singleValueOperationPressed:(UIButton *)sender {

    double result = 0.0;
    double value = [[display text] doubleValue];
    NSString *operation = [sender currentTitle];
    if([operation isEqualToString:@”sine”]){
    if(isSecondKeyPressed){
    if(!isRadiansPressed){
    operation = @”asineD”;
    }else{
    operation = @”asineR”;
    }
    }else{
    if(!isRadiansPressed){
    operation = @”sineD”;
    }else{
    operation = @”sineR”;
    }
    }
    }else if([operation isEqualToString:@”cos”]){
    if(isSecondKeyPressed){
    if(!isRadiansPressed){
    operation = @”acosD”;
    }else{
    operation = @”acosR”;
    }
    }else{
    if(!isRadiansPressed){
    operation = @”cosD”;
    }else{
    operation = @”cosR”;
    }
    }
    }else if([operation isEqualToString:@”tan”]){
    if(isSecondKeyPressed){
    if(!isRadiansPressed){
    operation = @”atanD”;
    }else{
    operation = @”atanR”;
    }
    }else{
    if(!isRadiansPressed){
    operation = @”tanD”;
    }else{
    operation = @”tanR”;
    }
    }
    }
    NSLog(@”operation %@”,operation);
    result = [[self calcBrain] performOperation:operation :value];
    userIsInTheMiddleOfEnteringANumber = NO;
    decimalAlreadyExist = NO;
    isSecondKeyPressed = NO;
    if([operation isEqualToString:@”1/x”] && [display.text doubleValue] == 0.0){
    [display setText:@”Error”];
    }else{
    [display setText:[NSString stringWithFormat:@”%g”,result]];
    }
    }

     

  11. for clear & all clear

    – (IBAction)allClearPressed {
    self.display.text = @”0″;
    userIsInTheMiddleOfEnteringANumber = NO;
    decimalAlreadyExist = NO;
    isSecondKeyPressed = NO;
    [[self calcBrain] setWaitingOperand: 0.0];
    [[self calcBrain] setCurrentOperand: 0.0];
    [[self calcBrain] setWaitingCalculation:nil];

    }
    – (IBAction)clearPressed {
    self.display.text = @”0″;
    userIsInTheMiddleOfEnteringANumber = NO;
    decimalAlreadyExist = NO;
    isSecondKeyPressed = NO;
    }

    Shift key with colour changing options

    – (IBAction)secondKeyPressed:(UIButton *)sender {
    UIButton *button = (UIButton *)sender;
    if(!isSecondKeyPressed){
    [button setBackgroundColor:[UIColor Color]];
    isSecondKeyPressed = YES;
    }else{
    [button setBackgroundColor:[UIColor Color]];
    isSecondKeyPressed = NO;
    }

    }

    Switching keys usually there in calculators for degrees and radians if only one key.
    – (IBAction)toggleButtonPressed:(UIButton *)sender {
    if(!isRadiansPressed){
    [sender setTitle:@”Degrees” forState:UIControlStateNormal];
    isRadiansPressed = YES;
    }else{
    [sender setTitle:@”Radians” forState:UIControlStateNormal];
    isRadiansPressed = NO;
    }
    }

    – (IBAction)toggleViewButtonPressed:(id)sender {
    if(!isViewKeyPressed){
    [sender setTitle:@”Portrait View” forState:UIControlStateNormal];
    isViewKeyPressed = YES;
    }else{
    [sender setTitle:@”Landscpae View” forState:UIControlStateNormal];
    isViewKeyPressed = NO;
    }
    }

    HOW of connecting evrything to the enter key and executing it from there…

    – (IBAction)enterPressed {

    [[self calcBrain] setCurrentOperand: [[display text] doubleValue]];
    userIsInTheMiddleOfEnteringANumber = NO;
    decimalAlreadyExist = NO;
    isSecondKeyPressed = NO;

    double result = [[self calcBrain] performWaitingCalculation];

    [display setText:[NSString stringWithFormat:@”%g”,result]];
    }

    PI KEY
    – (IBAction)piKeyPressed {
    self.display.text = [NSString stringWithFormat:@”%.08f”,M_PI];
    self.userIsInTheMiddleOfEnteringANumber = YES;
    }

    Delete / Backspace

    – (IBAction)backspaceKeyPressed {
    NSString *currentText = display.text;
    NSString *newText = [currentText substringToIndex:[currentText length] – 1];
    if([newText length] > 0){
    display.text = newText;
    }else{
    userIsInTheMiddleOfEnteringANumber = NO;
    display.text = @”0″;
    }
    }

     

     

  12. Decimal point can be done using…

    – (IBAction)decimalPressed {
    if(!decimalAlreadyExist){
    if([display.text isEqualToString: nil]){
    [display setText:@”0.”];
    }else{
    NSString *value = display.text;
    if([value rangeOfString:@”.”].location == NSNotFound){
    self.display.text = [self.display.text stringByAppendingString:@”.”];
    }
    }
    userIsInTheMiddleOfEnteringANumber = YES;
    decimalAlreadyExist = YES;
    }
    }

  13. I had orginally posted some of the above comments during March but i guess there are some issues… can anyone provide me some feedbacks on this code…

    (IBAction) btnEtcAction:(id)sender {
    int segNum = btnEtcOutlet.selectedSegmentIndex;
    //NSString* abc = @”1 + 1 + 1″;
    //int test;
    //lblStatusOutlet.text = [self removeFirstCharIfNegativeSign:@”t”];

    switch (segNum){
    case 0:     // +/-
    [self plusminusClicked];
    //lblStatusOutlet.text = @”+/-“;
    break;
    case 1:     // .
    [self pointClicked];
    //lblStatusOutlet.text = @”.”;
    break;
    case 2:     // Sq
    [self sqClicked];
    //lblStatusOutlet.text = @”Sq”;
    break;
    case 3:     // SqRt
    [self sqrtClicked];
    //lblStatusOutlet.text = @”SqRt”;
    break;
    case 4:     // =

    [self equalsClicked];
    //lblStatusOutlet.text = @”=”;

    //test = [self getHighestPriorityOperator:abc];
    //lblStatusOutlet.text = [NSString stringWithFormat:@”%d”,test];
    break;
    }
    }

  14. Thanks a lot 🙂 The code really helped me..

    Can you please tell me how to perform the operations successively and display the output?

    For ex: 24+ 35+ 2+75+89…

    Can we modify the same code to do the above?
    Looking forward for your support and favorable early reply.
     

     

  15. hi Deepak,
    i am a beginner and the code helped me a lot to understand.
    here's a additional ques : How i can clear just one by one digit
    from the left most digit instead of clearing the whole number string?
    kindly give me some idea.
    thank you. HAPPY NEW YEAR. 🙂

    • You can change the text alignment of UITextField from storyboard by clicking the object and changing to right alignment from the property sheet or you can do it by code
      textField.textAlignment = UITextAlignmentRight;

  16. Please tell me how to add numbers continuously without using '='.

    and whenever = is pressed number should be added automatically as it is in a real calculator

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.