UITextField text change event

后端 未结 21 1032
南方客
南方客 2020-11-22 06:49

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.

相关标签:
21条回答
  • 2020-11-22 07:45

    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!)
    
    }
    
    0 讨论(0)
  • 2020-11-22 07:46

    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)
    }
    
    0 讨论(0)
  • 2020-11-22 07:47

    SwiftUI

    If you are using the native SwiftUI TextField or just using the UIKit UITextField (here is how), you can observe for text changes like:

    SwiftUI 2.0

    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
                }
        }
    }
    

    SwiftUI 1.0

    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.

    0 讨论(0)
提交回复
热议问题