0

im trying to bind an Int to a textfield in SwiftUI. The initial value (50) is displayed in the form, but that value gets never updated. I checked this with the Text Output. Does anyone know, what is going wrong there?

struct AddFoodView: View {
    
    @Environment(\.presentationMode) var presentationMode 
    @State private var name:String = ""
    @State private var amountUnit:AmountUnit = .g
    @State private var amount:Int = 50
    
    var viewModel:FoodViewModel
    
        
    var body: some View {
        NavigationView {
            Form {
                
                Section(header:Text("Name")) {
                    TextField("Name", text:$name)
                }
                Section(header:Text("Portions")) {
                  
                    TextField("Amount", value: $amount, formatter: NumberFormatter()).keyboardType(.numberPad)
                    Text("Resulting \(amount)")

The Text ("Resulting (amount)") is never updated. Neither is self.amount updated if you check with debugger.

                        Text("g").tag(AmountUnit.g)
                        Text("ml").tag(AmountUnit.ml)
                    }.pickerStyle(SegmentedPickerStyle())
                }
                
                Button("Save") {
                    viewModel.addFood(name: self.name, amountUnit: self.amountUnit, amount: self.amount)
                    self.presentationMode.wrappedValue.dismiss()
                }
            }.navigationTitle("Detail")
        }
    }
}
mc77de
  • 63
  • 1
  • 9

0 Answers0