DEV Community

BC
BC

Posted on

Learn SwiftUI (Day 17/100)

Swift UI

  • TextField
  • Picker
  • Picker style
  • NavigationStack
  • Focus mode
  • Toolbar
import SwiftUI

struct ContentView: View {
    @State private var checkAmount:Double = 0
    @State private var numOfPeopleIndex:Int = 0
    @State private var tipsPercent:Int = 10
    @FocusState private var isFocused: Bool

    private let minPeopleCount = 2
    private let tipsPercentList: [Int] = [10, 15, 18, 20, 25, 0]


    var amountPerPerson: Double {
        checkAmount * (1.0 + Double(tipsPercent) / 100.0) / Double(numOfPeopleIndex + minPeopleCount)
    }

    var body: some View {
        NavigationStack {
            Form {
                Section{
                    TextField("Amount", value: $checkAmount, format: .currency(code: Locale.current.currency?.identifier ?? "USD"))
                        .keyboardType(.numberPad)
                        .focused($isFocused)
                    Picker("Number of people", selection: $numOfPeopleIndex) {
                        ForEach(2..<20) {
                            Text("\($0) People")
                        }
                    }
                    .pickerStyle(.navigationLink)
                }

                Section("Tip") {
                    Picker("Tip Percentage", selection: $tipsPercent) {
                        ForEach(tipsPercentList, id: \.self) {
                            Text("\($0)%")
                        }
                    }
                    .pickerStyle(.segmented)
                }

                Section("Amount per person") {
                    Text(amountPerPerson, format: .currency(code: Locale.current.currency?.identifier ?? "USD"))
                }

            }
            .navigationTitle("We Split")
            .toolbar {
                if isFocused {
                    Button("Done") {
                        isFocused = false
                    }
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Running:

Image description

Top comments (0)