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.
Step 4: According to header declaration add the methods in ViewController.m file
You can add these methods above the viewDidLoad method.
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