Swantewit
Swantewit

Reputation: 1076

Picker choice changing the TextField in SwiftUI

I want the user to be able to choose the currency they want to put in my app. But with this code:

import SwiftUI

struct ContentView: View {
    
    @State private var amount = 0.0
    @State private var currency = "USD"
    
    let currencies = ["PLN", "USD", "EUR", "GBP", "JPY"]
    
    var body: some View {
            Form {
                
                Picker("Currency", selection: $currency) {
                    ForEach(currencies, id: \.self) {
                        Text($0)
                    }
                }
                
                TextField("Amount", value: $amount, format: .currency(code: currency))
                    .keyboardType(.decimalPad)
            }
            }
      
    }

The currency choices made with Picker don't change the currency type in the TextField (it stays USD at all times, even after deletion). How to push the chosen currency code to the TextField?

Upvotes: 2

Views: 495

Answers (1)

Asperi
Asperi

Reputation: 257711

Format is not tracked to update TextField, you can do it forcefully using id depending on format parameter, like

 TextField("Amount", value: $amount, format: .currency(code: currency))
      .keyboardType(.decimalPad)
      .id(currency)                // << here !!

Tested with Xcode 13.2 / iOS 15.2

Upvotes: 2

Related Questions