mihema
mihema

Reputation: 358

SwiftUI: Value is not updated on Textfield using NumberFormatter like currency

I'd just like to know whether there's a bug in macOS or if I have to make changes in code with currency formatted TextFields.

My problem: just a simple TextField in SwiftUI like

TextField("amountOnDeadline",value: $startValue, formatter: Formatters.currencyFormatter)

The formatter ist pretty simple:

    static let currencyFormatter: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.maximumFractionDigits = 2
        return formatter
    }()

Build and run! The offered field is displayed as currency field. Great! But when I enter a number like 123, the field is reset to 0.00 € (or the value displayed on start). Only when I exactly mark the 0.00 without the currency symbol and enter a value, the new value is taken.

enter image description here

This is not very user friendly. Is it something I have to live with or is there a solution for this problem? e.g. a special config in NumberFormatter.

Upvotes: 1

Views: 794

Answers (1)

Nirav D
Nirav D

Reputation: 72410

Instead of using NumberFormatter you can use currency(code:) FormatStyle with TextField init(_:value:format:prompt:).

TextField("amountOnDeadline",value: $startValue, format: .currency(code: Locale.current.currencyCode ?? "EUR"))

This will not reset the field to 0.00 even if you remove the currency symbol.

Upvotes: 2

Related Questions