Reputation: 1303
I am implementing an app that allows user's to decimal numbers in a SwiftUI TextField. I achieved that using the following code.
@State private var total: Double = 0.0
TextField("Total", value: $total, formatter: NumberFormatter())
.keyboardType(.decimalPad)
The problem is that how do I validate that the TextField contains a number greater than zero and also that the user has input something and not left blank.
Here is my code:
var isValid: Bool {
total > 0
}
But the user can still leave the field blank and it will reset to the last double value they used.
Upvotes: 1
Views: 915
Reputation: 12115
You can work around with a classic text input:
struct ContentView: View {
@State private var input = ""
var body: some View {
VStack {
TextField("Total", text: $input)
.textFieldStyle(.roundedBorder)
.keyboardType(.decimalPad)
Button("Confirm") {
// do something with Double(input)
print(Double(input))
self.input = ""
}
.disabled( Double(input) ?? 0 <= 0 )
}
.padding()
}
}
Upvotes: 1