How can I detect any text changes in a textField? The delegate method shouldChangeCharactersInRange
works for something, but it did not fulfill my need exactly.
If you are using the native SwiftUI TextField
or just using the UIKit UITextField
(here is how), you can observe for text changes like:
From iOS 14, macOS 11, or any other OS contains SwiftUI 2.0, there is a new modifier called .onChange
that detects any change of the given state
:
struct ContentView: View {
@State var text: String = ""
var body: some View {
TextField("Enter text here", text: $text)
.onChange(of: text) {
print($0) // You can do anything due to the change here.
// self.autocomplete($0) // like this
}
}
}
For older iOS and other SwiftUI 1.0 platforms, you can use onReceive
with the help of the combine framework:
import Combine
.onReceive(Just(text)) {
print($0)
}
Note that you can use text.publisher
instead of Just(text)
but it returns the change instead of the entire value.