Checking for delete entry.
With the UIKit shouldChangeCharactersIn... delegate method the backspace is the equivalent of an empty string.
In the SwiftUI TextField .onChange() block it is necessary to use a capture list for the @State property being updated and do a comparison between that and the new value in the closure.
@State var textInput: String = ""
var body: some View {
TextField("numerical entries only", text: $textInput)
.onChange(of: textInput) { [textInput] newValue in
if newValue.count < textInput.count { print("- backspace detected") }
}
...
Post
Replies
Boosts
Views
Activity
There are a number of interesting responses here and great ideas.
Encountering a situation where I needed to enforce input using a SwiftUI TextField the same way I had done with the textField(_:shouldChangeCharactersIn:replacementString:) delegate method, I found simple filtering works nicely.
@State var textInput: String = ""
...
TextField("numerical entries only", text: $textInput)
.onChange(of: textInput) { newValue in
let numberCharacterSet = "0123456789"
textInput = newValue.filter { numberCharacterSet.contains($0) }
}