Share
Explore

Lab for building a *Tip Calculator* in SwiftUI

Here’s a complete, step-by-step lab for building a *Tip Calculator* in SwiftUI. I'll keep the instructions detailed and beginner-friendly, with plenty of validation checks along the way.
This project will reinforce learners’ comprehension of
Swift,
SwiftUI components, and
basic app-building concepts.

The code I provided here will work without any IBOutlets or IBActions because it’s written in SwiftUI, which is designed to eliminate the need for those connections.

Data Bindings:

Instead, SwiftUI uses data bindings with @State and reactive programming to automatically update the UI based on changes in the data.
Here's a quick breakdown of the differences:
IBOutlets and IBActions (UIKit): In UIKit, you create IBOutlets to reference UI components, and IBActions to handle user interactions. It requires you to manually connect the UI to your code in Interface Builder.
@State and Data Binding (SwiftUI): In SwiftUI, @State properties keep track of the data, and SwiftUI automatically updates the UI whenever these properties change. This removes the need for manual connections.

UIKIT - storyboard
drag components from the Library

SWIFT UI - everything is done programmatically
no manual procedures - there fore product builds can be automated


So, the SwiftUI code I shared will run without needing any IBOutlets or IBActions. It’s simpler, especially for beginners, since they won’t need to worry about connecting UI elements and actions in Interface Builder!

If you’ are a beginner, SwiftUI’s approach with @State is actually a very friendly way to introduce reactive and declarative programming in iOS development.


### **iOS Project: Tip Calculator**

**Objective**: Build a simple Tip Calculator app using SwiftUI.
The app will take a bill amount, allow the user to select a tip percentage, and display the calculated tip and total amount.
---
### **Project Setup**
#### Step 1: Create a New SwiftUI Project
1. **Open Xcode** and select **Create a new Xcode project**. 2. Choose **App** under **iOS** and click **Next**. 3. **Product Name**: Type `TipCalculator` 4. **Team**: Select your team if required (for beginners, you can select None if prompted). 5. **Organization Identifier**: Something like `com.yourname.TipCalculator` 6. **Interface**: SwiftUI. {up to now is was the old school StoryBoard } 7. **Language**: Swift 8. Click **Next**, choose a location to save the project, and click **Create**.
---
### **Building the Interface**
#### Step 2: Set Up the Basic Layout
1. Open `ContentView.swift`. 2. Replace the existing code with the following:
```swift import SwiftUI
struct ContentView: View { var body: some View { VStack(alignment: .leading, spacing: 20) { Text("Tip Calculator") .font(.largeTitle) .bold() Spacer() } .padding() } }
struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
3. **Explanation**: - `VStack`: Stacks elements vertically. - `.padding()`: Adds padding around the content for spacing. - This initial structure gives us a title and some spacing.
4. **Run the App**: Press `Cmd+R` to build and run. You should see the title "Tip Calculator" at the top of the screen.
megaphone

Starting the emulator (known as the Simulator in Xcode) is easy! Here’s how to do it in a few quick steps:

Step 1: Select Your Target Device

Open your project in Xcode.
Look at the toolbar near the top of the Xcode window. To the right of the play (▶️) and stop buttons, you’ll see a dropdown menu showing the currently selected device (e.g., “iPhone 14”).
Click on this device name dropdown to select a different simulated device if desired. If you're happy with the default, you can proceed with it.

Step 2: Run the App on the Simulator

Click the play button (▶️) in the top-left corner of Xcode’s toolbar, or press Cmd+R on your keyboard.
Xcode will start building your project, and then it will automatically launch the Simulator with the selected device.
Wait a moment for the Simulator to start and load your app. Once it opens, you should see your app’s interface!

Step 3: Interact with the App

The Simulator works just like a real iPhone or iPad, so you can tap, swipe, and enter text as you would on an actual device.
If you want to rotate the device in the Simulator, go to the Hardware menu at the top of the screen in the Simulator app and select Rotate Left or Rotate Right.

Stopping the Simulator

To stop the app, click the stop button (■) in the Xcode toolbar.
You can close the Simulator window or just quit it by pressing Cmd+Q when you’re finished.
And that’s it! You’re up and running in the Simulator.

Step 3: Add Bill Amount Input Field

1. Modify `ContentView` by adding a `TextField` to let the user input the bill amount.

```swift struct ContentView: View { @State private var billAmount = "" var body: some View { VStack(alignment: .leading, spacing: 20) { Text("Tip Calculator") .font(.largeTitle) .bold() Text("Bill Amount") .font(.headline) TextField("Enter bill amount", text: $billAmount) .keyboardType(.decimalPad) .padding() .background(Color(.systemGray6)) .cornerRadius(8) Spacer() } .padding() } } ```
2. **Explanation**: - `@State private var billAmount`: A state variable to store the bill amount input. - `TextField`: Allows the user to enter text. - `keyboardType(.decimalPad)`: Ensures the keyboard shows numbers for convenience.
3. **Run the App**: You should see a text field below the title where you can enter a bill amount.
---

Step 4: Add Tip Percentage Options

1. Add another `@State` variable and a `Picker` to let users select a tip percentage.

```swift struct ContentView: View { @State private var billAmount = "" @State private var tipPercentage = 15 let tipPercentages = [10, 15, 20] var body: some View { VStack(alignment: .leading, spacing: 20) { Text("Tip Calculator") .font(.largeTitle) .bold() Text("Bill Amount") .font(.headline) TextField("Enter bill amount", text: $billAmount) .keyboardType(.decimalPad) .padding() .background(Color(.systemGray6)) .cornerRadius(8) Text("Tip Percentage") .font(.headline) Picker("Tip Percentage", selection: $tipPercentage) { ForEach(tipPercentages, id: \.self) { percent in Text("\(percent)%") } } .pickerStyle(SegmentedPickerStyle()) Spacer() } .padding() } } ```
2. **Explanation**: - `@State private var tipPercentage`: Stores the selected tip percentage. - `Picker`: Creates a segmented control to select a percentage. - `ForEach`: Loops through `tipPercentages` array to display each percentage as an option.
3. **Run the App**: You should see a segmented control below the bill amount input with tip percentage options.
---
### **Calculating and Displaying the Tip**
#### Step 5: Calculate Tip and Total
1. Add computed properties to calculate the tip and total amounts based on the bill amount and selected tip percentage.
```swift struct ContentView: View { @State private var billAmount = "" @State private var tipPercentage = 15 let tipPercentages = [10, 15, 20] var tipValue: Double { let bill = Double(billAmount) ?? 0 let tip = Double(tipPercentage) return bill * tip / 100 } var totalAmount: Double { let bill = Double(billAmount) ?? 0 return bill + tipValue } var body: some View { VStack(alignment: .leading, spacing: 20) { Text("Tip Calculator") .font(.largeTitle) .bold() Text("Bill Amount") .font(.headline) TextField("Enter bill amount", text: $billAmount) .keyboardType(.decimalPad) .padding() .background(Color(.systemGray6)) .cornerRadius(8) Text("Tip Percentage") .font(.headline) Picker("Tip Percentage", selection: $tipPercentage) { ForEach(tipPercentages, id: \.self) { percent in Text("\(percent)%") } } .pickerStyle(SegmentedPickerStyle()) Text("Tip Amount: $\(tipValue, specifier: "%.2f")") .font(.headline) Text("Total Amount: $\(totalAmount, specifier: "%.2f")") .font(.headline) .bold() Spacer() } .padding() } } ```
2. **Explanation**: - `tipValue`: Calculates the tip as a percentage of the bill amount. - `totalAmount`: Adds the tip to the bill amount to get the total. - `Text` views at the end display the calculated tip and total.
3. **Run the App**: Now, you should see the calculated tip and total update automatically when you enter a bill amount and select a tip percentage.
---
### **Final Testing and Validation**
#### Step 6: Test the App
1. Enter different bill amounts and select various tip percentages to make sure the calculations are correct. 2. If the app functions as expected, congrats—your *Tip Calculator* is complete!
#### Step 7: Additional Challenges (Optional)
For extra learning, here are some extensions to consider: - Add validation to prevent non-numeric input. - Customize the app’s UI with colors and fonts. - Add an option for custom tip percentages.
---
This should be a solid lab for students to get familiar with SwiftUI basics and handling calculations! Let me know if you'd like any more modifications or explanations on any part of it. 😊
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.