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

Daniele B picture Daniele B · Aug 28, 2015 · Viewed 83.8k times · Source

I would like to detect the touch action on a UITextField.

It seems the "Touch Up Inside" action is not fired by touching inside the textfield.

Answer

Daniele B picture Daniele B · Aug 28, 2015

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")
}