Search code examples
iosswiftuitextfieldtouch-up-inside

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


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.


Solution

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