6

I have problem with add a Tap Gesture to my UITextField. Below code:

@IBAction func hanldeTap(recognizer: UITapGestureRecognizer) {
    println("works")
}

This action is associated with Tap Gesture Recognizer. In my TextField I have defined gestureRecognizer in OutletCollections. In my guess it should works. In described configuration gesture works e.x. for button or custom view.

Can you tell my what could go wrong and how can I fix this?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
LakaLe_
  • 454
  • 1
  • 6
  • 15

4 Answers4

11

UITextField has delegate methods, you might want to consider implementing those. Or just add action event to your textfield.

For example in viewDidLoad

textField.addTarget(self, action:Selector("textDidBeginEditing"), forControlEvents: UIControlEvents.EditingDidBegin)

Then implement this:

func textDidBeginEditing(sender:UITextField) -> Void
{
   // handle begin editing event
} 
Allan Macatingrao
  • 2,071
  • 1
  • 20
  • 28
2

If you set the textfields delegate, you can use;

optional func textFieldDidBeginEditing(_ textField: UITextField)

or

optional func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool

etc

roycable
  • 301
  • 1
  • 9
1
textField.addTarget(self, action:#selector(textDidBeginEditing), for: UIControl.Event.editingDidBegin)
manu
  • 556
  • 2
  • 9
  • 29
0

Swift 4.2

Adding to the accepted answer

Don't forget to add '#' before selector (with small s) i.e. #selector

textField.addTarget(self, action: #selector(textDidBeginEditing), for: UIControl.Event.editingDidBegin)

And do add @objc before the function. like

@objc func textDidBeginEditing(sender:UITextField) -> Void