This is a very short sample of an app that allows calculating how much every person should pay based on the check, the tip, and the number of people.
Credits: This app is based on the course “100 Days of SwiftUI” by @twostraws.
Code Sample
import SwiftUI
struct ContentView: View {
@State private var checkAmount = 0.0
@State private var peopleQuantityIndex = 0
@State private var tipPercentage = 18
@FocusState private var shouldShowKeyboard: Bool
static let currencyCode = Locale.current.currencyCode ?? "USD"
static let checkAmountFormat: FloatingPointFormatStyle<Double>.Currency = .currency(code: currencyCode)
var checkAmountWithTip: Double {
return ((Double(tipPercentage) / 100) + 1) * checkAmount
}
var checkAmountPerPerson: Double {
return checkAmountWithTip / Double(peopleQuantityIndex + 2)
}
var body: some View {
NavigationView {
Form {
Section {
TextField("Check Amount",
value: $checkAmount,
format: ContentView.checkAmountFormat)
.keyboardType(.decimalPad)
.focused($shouldShowKeyboard)
Picker("Number of people", selection: $peopleQuantityIndex) {
ForEach(2..<101) {
Text("\($0) people")
}
}
}
Section {
Picker("Tip percentage", selection: $tipPercentage) {
ForEach(0..<101) {
Text("\($0)%")
}
}
.pickerStyle(.menu)
} header: {
Text("How much do you want to tip?")
}
Section {
Text(checkAmountWithTip, format: ContentView.checkAmountFormat)
} header: {
Text("Total amount")
}
Section {
Text(checkAmountPerPerson, format: ContentView.checkAmountFormat)
} header: {
Text("Amount per person")
}
}
.navigationTitle("Split The Check")
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
Spacer()
Button("Done") {
shouldShowKeyboard = false
}
}
}
}
}
}