iOS/Swift: how to detect touch action on a UITextField

Swift 4 and higher:

class ViewController: UIViewController, UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == myTextField {
            print("You edit myTextField")
        }
    }
}

This is a delegate function.


It seems "Touch Up Inside" is not enabled for UITextField, but "Touch Down" works.

So the solution is as follows:

Swift 4.x

myTextField.addTarget(self, action: #selector(myTargetFunction), for: .touchDown)
@objc func myTargetFunction(textField: UITextField) {
    print("myTargetFunction")
}

Swift 3.x

myTextField.addTarget(self, action: #selector(myTargetFunction), for: UIControlEvents.touchDown)

@objc func myTargetFunction(textField: UITextField) {
    print("myTargetFunction")
}