'How do you get a bound variable to clear?
If $score is bound to score, how come the textfield won't clear? How do I make it clear? Also, how would I get "Enter Score" to show rather than "0"? Thanks.
import SwiftUI
struct keyType: View {
@State private var score: Double = 0
let formatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
return formatter
}()
func buttonClear() {
self.score = 0;
}
var body: some View {
VStack {
TextField("Enter Score", value: $score, formatter: formatter)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
Text(String(format: "Your Score: %.2f", score))
Button("CLEAR") {buttonClear()}
.padding()
}
}
}
Solution 1:[1]
If you use TextField(value: format:) the "empty" value is 0, but the prompt "Enter score" is only shown when the input string is "".
But you can use the standard TextField(text:) version and convert to a value manually. Then the prompt shows.
struct ContentView: View {
@State private var score: Double = 0
@State private var scoreTextInput = ""
func buttonClear() {
self.score = 0
self.scoreTextInput = ""
}
var body: some View {
VStack {
TextField("Enter Score", text: $scoreTextInput, onCommit: {
score = Double(scoreTextInput) ?? 0
})
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
Text("Your Score: \(score, specifier: "%.2f")")
Button("CLEAR") {buttonClear()}
.padding()
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ChrisR |
