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.
Swift Version tested:
//Somewhere in your UIViewController, like viewDidLoad(){ ... }
self.textField.addTarget(
self,
action: #selector(SearchViewController.textFieldDidChange(_:)),
forControlEvents: UIControlEvents.EditingChanged
)
Parameters explained:
self.textField //-> A UITextField defined somewhere in your UIViewController
self //-> UIViewController
.textFieldDidChange(_:) //-> Can be named anyway you like, as long as it is defined in your UIViewController
Then add the method you created above in your UIViewController
:
//Gets called everytime the text changes in the textfield.
func textFieldDidChange(textField: UITextField){
print("Text changed: " + textField.text!)
}
Swift 4 Version
Using Key-Value Observing Notify objects about changes to the properties of other objects.
var textFieldObserver: NSKeyValueObservation?
textFieldObserver = yourTextField.observe(\.text, options: [.new, .old]) { [weak self] (object, changeValue) in
guard let strongSelf = self else { return }
print(changeValue)
}
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.