Hello, I have an issue with formatting text in a TextField. I want to maintain formatting to two decimal places and have it respond to changes in the device's settings, as it currently does. However, I want to get rid of the problem with deleting the first character, which for some reason cannot be empty even though it should start with an empty value.
This is my code
extension Formatter {
static let numberFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.currencyCode = "GBP"
formatter.currencySymbol = ""
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
formatter.zeroSymbol = ""
return formatter
}()
}
struct HomeView: View {
@FocusState private var isFocused: Bool
@State var value: Double = 0
var body: some View {
VStack {
TextField("0.0",
value: $value,
formatter: Formatter.numberFormatter)
.focused($isFocused)
.border(.red)
.keyboardType(.decimalPad)
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
if isFocused {
Spacer()
Button("Done") {
isFocused = false
}
}
}
}
}
}
}
and here is the issue gif
I found similar problems in other forums like in https://www.hackingwithswift.com/forums/swiftui/textfield-with-initial-empty-value-for-a-number/12486/15516 but unfortunately uncomment.