How can I display and edit decimal values in SwiftUI TextField?

640 Views Asked by At

I am working on a SwiftUI project and I need to allow users to enter decimal values in a TextField. However, the default behavior of SwiftUI's TextField seems to only support integer values. I would like to know how I can modify the TextField to accept and display decimal values.

I have tried using the formatter: numberFormatter() property and keyboardType(.decimalPad) modifier on the TextField, but it doesn't seem to affect the behaviour. The TextField still only allows me to enter whole numbers.

Here is the code example. The list of items are look like below. I want to display and edit the price property of the object.

 @State private var items: [Item] = [
        Item(name: "Item 1", quantity: 10, price: 10.5),
        Item(name: "Item 2", quantity: 5, price: 12.5),
        Item(name: "Item 3", quantity: 3, price: 16000.3)
    ]

...

And the textfields are look like below,

...


HStack {
                    TextField("Item Description", text: $items[index].name)
                        .multilineTextAlignment(.center)
                    TextField("Quantity", value: $items[index].quantity, formatter: NumberFormatter())
                        .multilineTextAlignment(.center)
                    TextField("Price", value: $items[index].price, formatter: NumberFormatter())
                        .keyboardType(.decimalPad)
                        .multilineTextAlignment(.center)
                    
                }
1

There are 1 best solutions below

0
malhal On

You shouldn't init objects inline like: formatter: NumberFormatter() it's a memory leak, either use a static object or use the new convenience format: .currency. Also ForEach is not a for loop, you shouldn't have $items[index].name because it'll crash. Instead use ForEach($items) { $item in and then use text: $item.name and Item should be Identifiable.