0

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
    }

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Jessy
  • 157
  • 1
  • 10
  • 1
    Probably not what you want to here but why spend time and energy on creating a custom currency formatter when there are several built in formats to us? And why use such a strange format with currency code and symbol padded together? – Joakim Danielson Feb 03 '22 at 12:14
  • Why don't you use `NumberFormatter` with a `currency` style instead of creating a custom `Formatter`? – Dávid Pásztor Feb 03 '22 at 12:17
  • @Joakim Danielson @Dávid Pásztor thanks for replay. I really haven't got solutions yet, with `NumberFormatter` can we get that ? and I any suggestions for any library? but first preference is to create `TextField` reusable component. – Jessy Feb 03 '22 at 16:02
  • 1
    have you tried to search SO with `TextField currency`? Here is my favorite, https://stackoverflow.com/questions/67888195/i-want-to-add-sign-to-textfield-in-swiftui/67895810#67895810 – workingdog support Ukraine Feb 04 '22 at 00:21

0 Answers0