I am using a TextField to let the user add a price for something. To prevent the user adding other values as a number, I change the keyboard type to .decimalPad
.
The stringValue
is updated correct with the binding on every character change. My problem now is, that the doubleValue
is only updated, when the user presses the enter to commit. Unfortunately the decimal pad has no enter key to commit the input. So when I try to save the value to my core data object without pressing enter, 0 is saved instead the visible value (for example 17.12) in the text field. For testing now I will use another keyboard type with an enter button but for production this needs to be fixed somehow.
Do you have any ideas how this can be solved? Below a minimized example code to show the problem.
struct ContentView: View {
@State private var doubleValue: Double = 0.0
@State private var stringValue = "Test"
private let numberFormatter: NumberFormatter = {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .currency
return numberFormatter
}()
var body: some View {
Form {
TextField("", text: $stringValue)
.disableAutocorrection(true)
HStack {
Text("Price")
Spacer()
TextField("", value: $doubleValue, formatter: numberFormatter)
.fixedSize()
.keyboardType(.decimalPad)
}
// show live value changes
Text("\(stringValue)")
Text("Value: \(doubleValue)")
}
.padding()
}
func saveToCoreData() {
// save values into core data
}
}
I am using Xcode 12.2 and MacOS BigSur 11.0.1.
Edit belonging to asperis comment:
Your shared solution looks quite good, but as you can see in the screenshot it works not really correct:
After initial setup with value 0
I entered a 2
and then a 3
. The shown value is 2.03
which is indeed not what I wanted. Maybe I can enhance the approach of your hint.