0

I have a form where a user can enter several values to track charges. But the values are only stored in the properties when the user hits Enter if the values is added and the user selects the next field then the value for previous entered property remains at the initial value.

It there anything that needs to be set to accept normal change of fields?

Thanks.

import SwiftUI
import CoreData

struct CreateEditChargeView: View {
    @Environment(\.managedObjectContext) private var viewContext
    @Environment(\.presentationMode) var presentation
    private var isNew = true
    @ObservedObject var charge:Charge = Charge(entity: Charge.entity(), insertInto: nil)
    var selectedVehicle: Vehicle
    
    init(selectedVehicle: Vehicle, charge: Charge? = nil) {
        self.selectedVehicle = selectedVehicle
        if let charge = charge {
            isNew = false
            self.charge = charge
        } else {
            self.charge.id = UUID()
        }
    }
    @ViewBuilder
    var body: some View {
        Form {
            Section(header: Text("Basic")) {
                TextField("KM", value: $charge.odometer,formatter: Formatter.distanceFormatter)
                TextField("Price per Unit", value: $charge.pricePerUnit, formatter: Formatter.currencyFormatter)
                
            }
            
        }.navigationBarItems(leading: VStack{
            if presentation.wrappedValue.isPresented {
                Button(action: {
                    presentation.wrappedValue.dismiss()
                }) {
                    Text("Cancel")
                }
            }
        }, trailing: VStack {
            if presentation.wrappedValue.isPresented {
                Button(action: {
                    if isNew {
                        viewContext.insert(charge)
                        charge.vehicle = selectedVehicle
                    }
                    do {
                        try viewContext.save()
                    } catch {
                        ErrorHandler.handleError(error: error)
                    }
                    presentation.wrappedValue.dismiss()
                }) {
                    Text("Done")
                }
                
            }
        })
    }
}
MatzeLoCal
  • 392
  • 3
  • 14
  • 1
    This is by-design behavior of `TextField` with Formatter. If it does not fit your needs I recommend to consider approach like in https://stackoverflow.com/a/59509242/12299030. – Asperi Nov 22 '20 at 09:54
  • Thank you very much. I wasn't aware of that. – MatzeLoCal Nov 22 '20 at 12:48

0 Answers0