In SwiftUI, I have two textfields. One of them is String and the other should be Int. And I want textfields to appear empty before and after "save" functionality.
this is how I declare my Int variable
@State private var newItemDays: Int?
this is the textfields
TextField("Task Title", text: $newItemTitle)
.padding()
.background(Color.white)
TextField("Days to Countdown", value: $newItemDays, formatter: NumberFormatter())
.keyboardType(.numberPad)
.padding()
.background(Color.white)
And my Ok button saves them.
Button("OK") {
if let days = newItemDays {
let newItem = CountdownItem(title: newItemTitle, daysLeft: days)
self.store.add(item: newItem)
newItemTitle = ""
newItemDays = 0
isTextFieldVisible = false
}
}
If statement always return false even though I put integer there. If I remove optional from the declaration and make it equal to 0, it works but this time I see 0 at the textfields (it should appear empty)
Any help?
2
Answers
You can create a custom
NumberFormatter
& set thezeroSymbol
to be an emptyString
:And your
TextField
becomes:Use
format:
instead offormatter:
When
value
isInt?
it will appear empty initially.By the way, you shouldn’t init objects like
NumberFormatter()
insidebody
it is a memory leak, best stick to value types.