GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

TextField in the example iExpense: currency value is not updated

Forums > SwiftUI

I'm new to SwiftUI and studying the example iExpense

TextField("Amount", value: $amount, format: .currency(code: "USD")).keyboardType(.decimalPad)

No matter what I enter in the TextField, the value resolves to 0. Only if I empty the whole field, including the currency sign, data entry is possible

   

Hello, glad you are learning SwiftUI! Yes, you can click on 0.0 and change the value, or delete the entire field and enter only the value. My suggestion is that you change the variable amount to be nil. Then you can enter the value without any problems. Since you set the variable amount to nil, you also need to update the save function, add a default value, see the code below.

@State private var amount: Double? = nil

let item = ExpenseItem(name: name, type: type, amount: amount ?? 0.0)

   

I found that everything works fine if the currency format is converted to RMB. Just like this:

  TextField("Amount", value: $checkAmount, format: .currency(code: Locale.current.currency?.identifier ?? "USD"))

So, could this be a system bug? I'm using the iPhone 15 simulator in Xcode Version 15.4

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's all new Paywall Editor allow you to remotely configure your paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.