I\'m trying to get a numeric field updated so I\'m using a TextField with the formatter: parameter set. It formats the number into the entry field just fine, but does not up
Inspired by above accepted proxy answer, here is a ready to use struct with fair amount of code. I really hope Apple can add an option to toggle the behavior.
struct TextFieldRow: View {
var value: Binding
var title: String
var subtitle: String?
var valueProxy: Binding {
switch T.self {
case is String.Type:
return Binding(
get: { self.value.wrappedValue as! String },
set: { self.value.wrappedValue = $0 as! T } )
case is String?.Type:
return Binding(
get: { (self.value.wrappedValue as? String).bound },
set: { self.value.wrappedValue = $0 as! T })
case is Double.Type:
return Binding( get: { String(self.value.wrappedValue as! Double) },
set: {
let doubleFormatter = NumberFormatter()
doubleFormatter.numberStyle = .decimal
doubleFormatter.maximumFractionDigits = 3
if let doubleValue = doubleFormatter.number(from: $0)?.doubleValue {
self.value.wrappedValue = doubleValue as! T
}
}
)
default:
fatalError("not supported")
}
}
var body: some View {
return HStack {
VStack(alignment: .leading) {
Text(title)
if let subtitle = subtitle, subtitle.isEmpty == false {
Text(subtitle)
.font(.caption)
.foregroundColor(Color(UIColor.secondaryLabel))
}
}
Spacer()
TextField(title, text: valueProxy)
.multilineTextAlignment(.trailing)
}
}
}