iosswiftuitextfieldswift4target-action

How to identify which UITextField was changed with textFieldDidChange


I am using several UITextFields and want to do anytime anything changes in any one of them.

It looks basically like:

@IBOutlet weak var f1: UITextField!
@IBOutlet weak var f2: UITextField!
@IBOutlet weak var f3: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    f1.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
    f2.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
    f3.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
}

@objc func textFieldDidChange(_ textField: UITextField) {
    // Data in one of the fields changed.
    if self.view.tag == 1 {
        print("field 1")
    } else {
        if self.view.tag == 2 {
            print("field 2")
        }
        //...
    }
}

As you can see, I've tried setting tags, but not sure how to access them here.

I’m using XCode 9.01 and Swift 4.


Solution

  • You don't need tags since you have outlets. Just compare the textField parameter to each of your outlets:

    @objc func textFieldDidChange(_ textField: UITextField) {
        if textField == f1 {
            print("field 1")
        } else if textField == f2 {
            print("field 2")
        } else if textField == f3 {
            print("field 3")
        }
    }