I would like to create a custom Formatter
to TextField
. Here I have done some workaround but it's not working as expected.
We should show text in the formate of USD$ 200.00
. USD$ prefix should show in the text field.
struct ContentView: View {
@State var amount = ""
var body: some View {
VStack {
TextField("USD$ 0.00",
value: $amount,
formatter: DollorFormatter())
.keyboardType(.namePhonePad)
}
.padding(.horizontal)
}
}
class DollorFormatter: Formatter {
var text = ""
override func string(for obj: Any?) -> String? {
return text
}
override func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
text = String(format: "USD$ %.2f", string.toDouble)
print(text)
obj?.pointee = text as AnyObject
return false
}
}
extension String {
var toDouble: Double {
return Double(self) ?? 0.0
}