I'm trying to make a dead simple app that changes the format of a text field when the user selects their preferred currency
struct ContentView: View {
@State var currency = "EUR"
@State var amount = 0.0
let currencies = ["GBP", "USD", "EUR", "WON", "LKR"]
var body: some View {
Form {
TextField(
"Amount",
value: $amount,
format: .currency(code: currency)
)
Picker("Currency", selection: $currency) {
ForEach(currencies, id: \.self) {
Text($0)
}
}
.pickerStyle(.segmented)
Section {
Text("Selected: \(currency)")
}
}
.navigationTitle("Currency Picker Issue")
}
}
With this attempt there are two main issues:
- Selecting a new currency doesn't actually change the format of the amount field
- Entering a new value into the amount does not save the value (it shoots back to zero as soon as the field loses focus
Why is this happening?
Is there any way to implement something like this in SwiftUI?
CodePudding user response:
For you 1. issue, you can force SwiftUI to redraw by using .id
on the TextField:
TextField(
"Amount",
value: $amount,
format: .currency(code: currency)
)
.id(currency) // forces redraw of view when changed
your 2. issue I cannot reproduce, at least as long as you enter a valid amount.