Greg
Greg

Reputation: 707

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.

Upvotes: 0

Views: 274

Answers (2)

Paulo Mattos
Paulo Mattos

Reputation: 19339

A quick, modest improvement over rmaddy’s answer:

@objc func textFieldDidChange(_ textField: UITextField) {
    switch textField {
    case f1: print("field 1")
    case f2: print("field 2")
    case f3: print("field 3")
    default: fatalError(“Unknown field: \(textField)”)
    }
}

Besides using a switch — which might slightly improve code readability one may argue — this version also triggers a runtime error if an unexpected text field is passed. Luckily, this might just catch a programming error later on ;)

Upvotes: 3

rmaddy
rmaddy

Reputation: 318794

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

Upvotes: 3

Related Questions