UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

TextField number treated as text

Forums > SwiftUI

Using SwiftData where Transaction has [Transfer] children and Transfer has one Transaction parent

Table of Transfers with TextField binding as Binding(transfer).value works fine but a Table of Transactions using Binding(transaction).transfers[index].value makes it impossible to enter more than one digit before the TextField resets

Is there a problem with Binding? Why might a number be treated as text?

   

Show your code for the text field.

If you use the value argument for the text field, you should be able to bind the text field to a number, such as in the following code:

@State private var billAmount: Double = 0

TextField("Bill Amount", value: $billAmount, formatter: .number)

When you use the value argument, you also have to supply a formatter. See also the following Hacking with Swift article:

https://www.hackingwithswift.com/quick-start/swiftui/how-to-format-a-textfield-for-numbers

1      

This was the problematic code

TextField("Debit",
  value: Bindable(transaction).transfers[index].debitAmount,
  format: .number.precision(.fractionLength(2)).sign(strategy: .never)
  )

I read that one shouldn't use depth or index in a binding so I changed the code which now looks like:

if let transfer = transaction.transfers.first(where: {$0.account?.name == activeAccount.name}) { 
  TextField("Debit",
  value: Bindable(transfer).debitAmount,
  format: .number.precision(.fractionLength(2)).sign(strategy: .never)
  )

(this happens inside a TableColumn whose rows are Transaction objects)

Also now using Bindable since pairedTransfer is a SwiftData object, not sure if that is the right way.

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire 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.