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

suggest change

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


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

Table Of Contents
12 UIView
15 UIColor
26 UIImage
28 CALayer
30 NSDate
40 iBeacon
49 NSTimer
79 NSURL
87 AWS SDK
96 NSData
101 Segues
104 EventKit
105 NSBundle
106 SiriKit
111 StoreKit
117 3D Touch
119 Keychain
122 Block
126 UITextField Delegate
141 AirDrop
144 UISlider
145 Carthage
146 HealthKit
151 plist
157 MVVM
164 UIPhoenix
166 Simulator
168 NSArray
169 OpenGL
175 Core Data
179 MyLayout
180 UIFont
189 Security
200 Codable