UITextField text change event

后端 未结 21 1009
南方客
南方客 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!)
    
    }
    

提交回复
热议问题