Search code examples
iosswiftswift4

Swift 4 - identifying only one text field as delegate for editingDidEnd etc


I've kept this question free of specific context because I'm sure it will be helpful for others :

I have 2 IB outlet text fields :

@IBOutlet weak var textField1: UITextField!
@IBOutlet weak var textField2: UITextField!

I want to be able to disable buttons on my page until both have been filled out properly so I'm using the following delegates in ViewDidLoad() (I have added TextFieldDelegate to my VC.)

override func viewDidLoad() {
    textField1.delegate = self
    textField2.delegate = self
}

I then have some functions I will use to do the form validation and to take specific actions but to keep it simple let's say it simply prints to the console.

What I want to do is only check for validation in textField1 and not in textField2. I.e. the desired output is that this prints for when user begins editing textField1 but if user edits textField2 nothing is printed.

I'm currently using :

func textFieldDidBeginEditing(_ textField1: UITextField) {
    print("TextField did begin editing method called")
}

But that is printing when either textField is edited.

I thought I've specified _ textField1 so not sure why both are triggering it?

There are some answers solving similar problems for Swift 3 and earlier. In particular one answer referenced this link http://sourcefreeze.com/uitextfield-and-uitextfield-delegate-in-swift/ which i've found useful but am stuck on this error.


Solution

  • UITextField delegate method allows you to identify that which textField is begin editing so you just need to check whether it's your 1st textField or not like this.

    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField === self.textField1 {
            print("TextField did begin editing method called")
            // Do your Validate for first text field
        } else {
            //Do Nothing
        }
    }