0

I have the following scenario: I'm creating a Form where the user can input an amount in a TextField. Additionally the user can select a currency through a Picker. The amount is formatted with a NumberFormatter and I want to update the text whenever the user changes the currency.

@State private var currencyCode = "EUR"

That's the formatter:

private let currencyFormatter: NumberFormatter = {
    var formatter = NumberFormatter()
    formatter.numberStyle = .currency
    formatter.currencyCode = $currencyCode // something like this, but that's not working!
    return formatter
}()

The form looks like this:

Form {
    Section {
        TextField("Enter a description", text: $reason)
        TextField("Amount", value: $amount, formatter: currencyFormatter)
            .keyboardType(.decimalPad)
    }

    Section {
        Picker(selection: $currencyCode, label: Text("Currency")) {
            ForEach(codes, id: \.self) { code in
                Text(code)
            }
        }
    }
}
gpichler
  • 2,181
  • 2
  • 27
  • 52
  • So, you're just wondering how to update the text upon selecting a currency from the picker? – David Chopin Sep 26 '19 at 17:30
  • Basically yes, however the text depends on the currency formatted. So the currency code of the formatted somehow needs to be changed from the picker. – gpichler Sep 26 '19 at 21:23

1 Answers1

1

First, you need to remove the $. $currencyCode gives you a Binding<String>, but you want the value, not the binding to the value. (See this answer where I explain Binding.)

Second, you want to use a computed property, because your number formatter needs to change based on your selected currencyCode. Put this inside your view struct:

private var currencyFormatter: NumberFormatter {
    let formatter = NumberFormatter()
    formatter.numberStyle = .currency
    formatter.currencyCode = currencyCode
    return formatter
}
John M.
  • 8,892
  • 4
  • 31
  • 42
  • Alright, I understand! Thanks for your explanation. The `TextField` however always resets my input whenever I pick a new value from the `Picker`. – gpichler Sep 27 '19 at 07:49
  • OK, so it works perfectly fine when I set a default value to `@State private var amount: Double = 0.0`. However if I make it optional the formatter does not work. – gpichler Sep 27 '19 at 13:39
  • I assume you mean the formatter returns a blank string if amount is nil? – John M. Sep 27 '19 at 14:56
  • As soon as I make `@State var amount: Double?` and type in a value, it always gets reseted (blank textfield) once I select a different `Picker` value. Also the text does not get formatted as currency string. – gpichler Sep 28 '19 at 14:21
  • Figured it out now, thanks for your help. I'm using a custom `@Binding` variable and set that as text for the `TextField`, this answer helped me with this https://stackoverflow.com/questions/56799456/swiftui-textfield-with-formatter-not-working – gpichler Sep 28 '19 at 15:04