Post

Replies

Boosts

Views

Activity

Reply to Is it possible to dynamically update the currency formatting of SwiftUI TextField?
I understand that you want to change the currency symbol, but also want to change the TextField to show the new currency in the proper format. I had the same problem. While working on it I realized that currency symbol and number formatting are actually different things, and not necessarily connected. If an American speaks about ten thousand dollars, he will write "$10,000.00". If a German speaks about a thousand Euros, he will write "10.000,00 €". And if he speaks about a thousand dollars, in his own country, he will probably write "10.000,00 $". A Frenchman will write a thousand Euros as "10 000,00 €". A Dutchman will write "€ 10.000,00". Etc. So, to properly format a currency you need to know both the valuta and the region where the expression is used. This information is in SwiftUI captured in NumberFormatter.locale, which contains both a language code and a country code. Examples in String form: "en-US", "en-GB", etc. The following code takes care of that. A trick is used to update the TextField whenever another locale is chosen in the Picker. See the function setLocale(:). This is because the TextField does not monitor the .locale property of the NumberFormatter class object, and I know of no way to make it do so. Therefore amount, which is monitored, is changed and then changed back. An ugly hack, but I think safe and it works (at least until the compiler optimizes it away... and there are ways around that I suppose.) Anyway, I would like to learn of a more Swifty way. I hope this is what you are looking for! import SwiftUI struct ContentView: View { private var numberFormatter: NumberFormatter init(numberFormatter: NumberFormatter = NumberFormatter()) { self.numberFormatter = numberFormatter self.numberFormatter.usesGroupingSeparator = true self.numberFormatter.numberStyle = .currency self.numberFormatter.locale = Locale(identifier: "nl-NL") } @State private var amount = 1234567.89 let locales = ["nl-NL", "de-DE", "fr-FR", "en-US", "en-GB", "th-TH", "az-AZ"] @State private var locale = "nl-NL" @State private var newLocale = "nl-NL" func setLocale(to locale: String) { numberFormatter.locale = Locale(identifier: locale) amount += 1 amount -= 1 } var body: some View { NavigationView { Form { Text("Current locale: \(locale)") TextField("Amount", value: $amount, formatter: numberFormatter) Picker("Choose your new locale:", selection: $newLocale) { ForEach(locales, id: \.self) { locale in Text(locale) } } .onChange(of: newLocale) { newValue in setLocale(to: newLocale) locale = newLocale } } } } } Disclaimer: Only tested on the XCode simulator.
May ’22