An interesting example. In my opinion, this is a bug of iOS 13 beta 3+ and you should better send a bug report soon.
What must be changed in the code so that entered numerical values are stored in the Decimal property again?
As far as I tried, creating a Binding String <-> Decimal seemed nearly working:
private let decimalFormatter: NumberFormatter = {
// let formatter = MyNumberFormatter()
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.generatesDecimalNumbers = true
return formatter
}()
struct DecimalBindingView: View {
@Binding var model: Model
var stringBinding: Binding<String>
init(model: Binding<Model>) {
_model = model
stringBinding = Binding(get: {
decimalFormatter.string(for: model.wrappedValue.decimalQuantity) ?? ""
}, set: {
if let decimal = decimalFormatter.number(from: $0) as? NSDecimalNumber {
model.wrappedValue.decimalQuantity = decimal as Decimal
}
})
}
var body: some View {
Form {
Section {
Label {
Text("This text field does not work correctly. \nIt doesn't write the value back to the property when the field loses focus or you click Enter.")
} icon: {
Image(systemName: "xmark.circle").foregroundColor(Color.red).scaleEffect(1.4)
}
.lineLimit(10)
TextField("Input a number of type decimal…", text: stringBinding)
}
Section {
TextField(
"Sample field, so you can leave the other field",
text: $model.someText)
}
}
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: