Ignoring the COVID-19 world we live in right now, going out to eat is something we all love and while we don’t mind tipping the wait staff, we often don’t understand the tip calculation. Hence, I thought that helping you make a tip calculator would be the best way to get you started on making your first iOS app. Don’t worry if you haven’t built anything in iOS prior to this, with the right instructions, it’s not hard. If I can do it, so can you. The rest of this article is structured as follows,
- We will talk a little bit about what the app is
- Talk about the starter project and Xcode environment
- Discuss some storyboard concepts and write some code
- Finally, conclude with what you can do next after building this app
Tip Calculator
You will build a simple tip calculator where the user can enter their bill amount and push a button to calculate their tip. They can enter the tip percentage and edit the amount of tip they want to pay and before anything, let’s get familiar with our Xcode environment.
Xcode Environment
Download the starter project attached and open the Tipcalculator.xcodeproj and run the project and you can expect to see an empty shell of an app that doesn’t do much. That’s ok, you will add all the functionality as you read through this tutorial. Open Main.storyboard file and you will see the following
You can see our UIElements as being UITextField (s), UILabel (s) and UIButton to calculate the amount. UITexField, what? Ok, think of it this way
- UITextField: A UIControl i.e. a place where the user can enter information (editable)
- UILabel: A place where we can show the user information (uneditable)
- UIButton: A control that the user can tap/click/push and expect to see something
For this tutorial, everything is arranged for you so you don’t have to worry about positioning elements (auto-layout). If you are feeling overwhelmed in this new environment, don’t worry you will know more once we discuss some iOS concepts.
iOS Concepts
Storyboards
Open Main.storyboard and you will find yourself in the interface builder (IB – try to remember, you will see ‘IB’ later), and what you are looking at is the Graphical User Interface (GUI or just UI) for our app. Interface builder is part of Xcode and it’s there for you to build the UI for your app. You can drag and drop GUI elements such as UITextField, UILabel, UITableView etc and position them in our app using auto-layout.
Storyboard is just one of the many ways in which you can build your iOS app UI, there are other more advanced techniques that you can learn once you are more familiar with Xcode.
This entire process can be summed up as, you are an artist, Swift is your favourite paintbrush, Storyboard is the canvas and your app (tip calculator) is your masterpiece.
Connect the storyboard to code
To connect your storyboard elements to code, let’s bring up the assistant editor
You will see the assistant editor on the right of the screen.
The Assistant Editor opens the code for UIViewController (back-end) where you can control aspects of your app by writing Swift code. Now let’s start connecting our front-end to back-end
Ctrl-Drag (press ctrl on keyboard and hold the point) the “bill” textfield to the UIViewController as seen below
You can name the resulting IBOutlet whatever you want but for this tutorial let’s name it “billTF” as seen in the screen below.
p.s. TF = TextField, just something I normally do to remember the type of variable it is.
Next,
- Ctrl-drag the %tip and call it tipPercentageTF
- Ctrl-drag “tip amount” label and call it tipAmountLbl
- Ctrl-drag “total amount” label and call it totalAmountLbl
Lastly, ctrl-drag from the calculate button and name it calculateTip
Notice, this is a bit different in that, it’s an IBAction and not an IBOutlet. Wait, IB…what?
IBOutlets & IBAction
Remember, ‘IB’ from the “iOS Concepts” section earlier? First, let’s start with the IBOutlet, as Apple’s official docs say, “an outlet is a property of an object that references another object, and outlets are a form of object composition which is a dynamic pattern”. So in case of this example, the ViewContoller has a property called billTF which is a connection between Interface Builder and ViewController. This allows you to trigger changes to the ViewController code from Interface Builder or vice versa. Using IBOutlets you have set up a two way communication channel between the Interface Builder and ViewController.
An IBAction is a function that has a return type void. Here it triggered it on your .touchUpInside event. It’s a way in which you tellInterface Builder that when the user taps the button, call this method in the ViewController.
In summary, what you are creating here are Interface Builder (IB) outlets and Actions. Setting up and configuring outlets is a way to establish communication between your GUI and code i.e. between front-end and backend.
I think it’s time to write some Swift code now, hmm, let’s do one more thing before that,
Limit input
Ok more like doing two things before that,
- Select the bill textField
- Select the attributes inspector e.g,
- From the Keyboard Type drop down select Number Pad e.g.,
Since you are building your first iOS app, I am keeping it simple and setting the Keyboard Type to Number Pad, it ensures you always get a numeric value from the user.
Calculate Tip
Ok time to write some Swift code 🙂 In the ViewController navigate to the calculateTip method and add the following code
guard let billAmt = billTF.text,
!billAmt.isEmpty else {
print("Bill Amount error")
return
}
guard let tipPercent = tipPercentageTF.text,
!tipPercent.isEmpty else {
print("Tip Percentage error")
return
}
You are using Guard to check
- If there’s text in the bill and tip percent text field. Notice, how there’s a “,” before the start of the next line after the line with guard let, that’s your logical “and” operator
- Whether or it’s empty
If it doesn’t meet the above conditions you print an error message to the console and transfer execution out of the program.
Ok now that you have the bill amount and tip percentage, you can calculate the tip amount and the total bill. Below the above code in the calculateTip method, write the following code,
let billDecimal = Decimal(string: billAmt)!
let percentDecimal = Decimal(string: tipPercent)!
var tip = (percentDecimal / 100) * billDecimal
var tipR = Decimal()
NSDecimalRound(&tipR, &tip, 0, .up)
tipAmountLbl.text = "\(tipR)"
totalAmountLbl.text = "\((billDecimal + tipR))”
Here’s what happens in the above code
- You parse the string values of bill and percent to Decimal (for calculations involving money NSDecimal is just more accurate than Double or Float)
- To find out how much does the tip percentage amount to of the bill total, we divide the percentage by hundred and multiply it by the bill
- You round up the resulting amount to 0 decimal places
- Then you update the UILabel outlets for tip amount and the total amount with your calculated values.
p.s. I realise the user may end up paying more due to rounding up tip amount, but come on you have to feel for the wait staff, they work very hard and these people have lost a lot in the COVID-19 crisis.
iOS Concepts: guard statement
guard statements were introduced in Swift 2.0 with one of it’s goals being, making Swift code easier to read. Swift has optionals and you can often get caught in a series of “if let” statements which you can call the “pyramid of doom”. The above code without guard would be something like,
if let billAmt = billTF.text {
if !billAmt.isEmpty {
That’s a very small example, the indentation can continue increasing, get messy and resemble the “pyramid of doom”.
Press cmd+r on the keyboard and run your app in the simulator and marvel at your creation. You just made an iOS app, you’re awesome.
Summary
In this tutorial you made a very simple yet, fully functional iOS app and you got familiar with the Xcode environment, wrote some calculation logic in Swift and learned some iOS concepts. This was a very simple example and I encourage you to continue on your iOS journey, starting with improving the tip calculator you just wrote.
Where to go from here?
You can download the final project from here and from here on, you can do a number of things,
- Learn more about interface builder: https://developer.apple.com/xcode/interface-builder/
- Drag and drop a UISegmentedControl in your storyboard
- Specify auto-layout constraints to arrange it
- Provide predefined tip percentage options e.g. 10 %, 15%, 20%
- Use a UIStepper to set the number of people eating and adjust the tip amount and total based on that
- Or maybe search for currency calculator apps on the iOS app store and try to mimic their functionality e.g. https://apps.apple.com/us/app/tip-calculator-gold/id532457588
As usual, if you find any of my posts useful support me by buying or even trying one of my apps on the App Store.
Also, if you can leave a review on the App Store or Google Play Store, that would help too.
0 Comments