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?
You can create a custom NumberFormatter
& set the zeroSymbol
to be an empty String
:
let formatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.zeroSymbol = ""
return formatter
}()
And your TextField
becomes:
TextField("Days to Countdown", value: $newItemDays, formatter: formatter)