I am trying to make a test tip calculate and I am missing something. Need help to understand how to do this to see what I am doing wrong

I am new to SwiftUI. What am I missing?

struct ContentView: View {

@State private var total: String = ""

@State private var ten = false
@State private var twelve = false
@State private var fifteen = false
@State private var eighteen = false
@State private var twenty = false

var body: some View {
    GeometryReader { geometry in
    VStack {
        HStack {
            Group {
                TextField(
                    "Total",
                    text: $total
                )
                .disableAutocorrection(true)
                }
                .textFieldStyle(.roundedBorder)
                .frame(
                    width: geometry.size.width*0.8,
                    alignment: .center
                )
                .position(x: UIScreen.main.bounds.width/2)
                .padding(.top, 80)
            }
        }
        HStack {
            Button("10%") { ten.toggle() }
            Button("12%") { twelve.toggle() }
            Button("15%") { fifteen.toggle() }
            Button("18%") { eighteen.toggle() }
            Button("20%") { twenty.toggle() }
            
            if ten { Text("10%") }
            if twelve { Text("12%") }
            if fifteen { Text("15%") }
            if eighteen { Text("18%") }
            if twenty { Text("20%") }
        }
        .position(x: UIScreen.main.bounds.width/2)
        .frame(
            width: geometry.size.width*0.8,
            alignment: .center
        )
        .padding(.top, 130)
    }
}

@State private var numberOfPeople: Int = Int()
@State private var peopleCount: String = ""
@State private var tipPercentage: Int = Int()
@State private var checkAmount: Int = Int()

var totalPerPerson: Double {
    let peopleCount = Double(numberOfPeople + 2)
    let tipSelection = Double(tipPercentage)

    let tipValue = Double(checkAmount) / 100 * Double(tipSelection)
    let grandTotal = checkAmount + tipValue
    let amountPerPerson = grandTotal / peopleCount

    return amountPerPerson
}

func Section() {
    Text(totalPerPerson, format: .currency(code: Locale.current.currencyCode ?? "USD"))
}

}

Please clarify what behavior you are trying to achieve. What should happen when the user enters a number into the text field and then taps a percentage?

2 Likes
Terms of Service

Privacy Policy

Cookie Policy