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)
}
You shouldn't init objects inline like:
formatter: NumberFormatter()it's a memory leak, either use a static object or use the new convenienceformat: .currency. AlsoForEachis not a for loop, you shouldn't have$items[index].namebecause it'll crash. Instead useForEach($items) { $item inand then usetext: $item.nameandItemshould beIdentifiable.