Search code examples
swiftuitextfieldnsdecimalnumber

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


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)
}

Solution

  • You're probably looking for a number formatter that's configured for decimals. Add this somewhere before body:

    let numberFormatter: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter
    }()
    

    Then you can use it like so:

    TextField("Quantity", value: $items[index].quantity, formatter: numberFormatter).multilineTextAlignment(.center)