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

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any iOS Question?