Home > Net >  How to trigger textFieldDidChangeSelection only for a specific UITextField?
How to trigger textFieldDidChangeSelection only for a specific UITextField?

Time:06-17

In a view with multiple UITextField elements, textFieldDidChangeSelection will trigger for any editing done in any UITextField. Can we perform some action inside this function only when a certain UITextField is edited?

class MyViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var text1: UITextField!
    @IBOutlet weak var text2: UITextField!
    @IBOutlet weak var text2: UITextField!

     //..........

     func textFieldDidChangeSelection(_ textField: UITextField) {
          print(textField.text) // this code should run only for text1 for example
    }

}

CodePudding user response:

You just need to compare the textField to the one you want:

func textFieldDidChangeSelection(_ textField: UITextField) {
    guard textField === text1 else { return }
    print(textField.text)
}

Note that you should use the identity operator === not the equality operator ==.

CodePudding user response:

You can do something like this:

func textFieldDidChangeSelection(_ textField: UITextField) {
    if textField === text1 {
        print(textField.text) // this code should run only for text1 for example
    }
}
  • Related