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)
}
}
}
}