I am trying to implement the ability to change a currency value in an edit mode detailed view, but I am struggling to get formatted input for numeric values working.
struct JobDetailView_Edit: View {
@State var jobDetails: JobDetails
var currencyFormatter: NumberFormatter = {
let f = NumberFormatter()
f.numberStyle = .currency
return f
}()
var body: some View {
Form {
Section(header: Text("General")) {
HStack {
Text("Job Name")
Spacer()
TextField($jobDetails.jobName)
.multilineTextAlignment(.trailing)
}
TextField($jobDetails.hourlyRateBasic, formatter: currencyFormatter)
}
... other unimportant code...
The data is passed in correctly, and the textfield displays the formatted value which is stored in $jobDetails.hourlyRateBasic, however, I cannot edit the field as I would be able to if it were a string. If I try to edit the field then press enter in the simulator, I get the following error message:
[SwiftUI] Failure setting binding's value. The supplied formatter does not produce values of type Double. This may be resolved by ensuring the binding and the output of the formatter are of the same type.
FYI $jobDetails.hourlyRateBasic is of type double.
I have created a component that wraps around a UITextfield.
You can check it out here https://github.com/youjinp/SwiftUIKit
Here's the demo
Ben Scheirman created a Tip Calculator that used a TextField with a currency formatter. The difference between his code and yours is that he stored the currency value in a Double?. NumberFormatter returns a NSNumber?.
You can see his code at https://github.com/nsscreencast/397-swiftui-tip-calculator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With