iOS Actions when a user has started/ended interacting with a textfield


Example

For Swift 3.1:

In the first example one can see how you would intercept the user interacting with a textfield while writing. Similarly, there are methods in the UITextFieldDelegate that are called when a user has started and ended his interaction with a TextField.

To be able to access these methods, you need to conform to the UITextFieldDelegate protocol, and for each textfield you want to be notified about, assign the parent class as the delegate:

class SomeClass: UITextFieldDelegate {
    
    @IBOutlet var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }

}

Now you will be able to implement all the UITextFieldDelegate methods.

To be notified when a user has started editing a textfield, you can implement textFieldDidBeginEditing(_:) method like so:

func textFieldDidBeginEditing(_ textField: UITextField) {
    // now you can perform some action 
    // if you have multiple textfields in a class, 
    // you can compare them here to handle each one separately
    if textField == emailTextField {
        // e.g. validate email 
    } 
    else if textField == passwordTextField {
        // e.g. validate password 
    } 
}

Similarly, being notified if a user has ended interaction with a textfield, you can use the textFieldDidEndEditing(_:) method like so:

func textFieldDidEndEditing(_ textField: UITextField) {
    // now you can perform some action 
    // if you have multiple textfields in a class, 
    // you can compare them here to handle each one separately
    if textField == emailTextField {
        // e.g. validate email 
    } 
    else if textField == passwordTextField {
        // e.g. validate password 
    } 
}

If you want to have control over whether a TextField should begin/end editing, the textFieldShouldBeginEditing(_:) and textFieldShouldEndEditing(_:) methods can be used by return true/false based on your needed logic.