1

I want to write a custom code on double tap on UITextField and block the default text editing and popup of the keyboard. I've tried the following and nothing has worked for me so far. Kindly help me solve this problem.

let gestureArray = NamTxtBoxVal.gestureRecognizers
var tapGesture = UITapGestureRecognizer()
for idxVar in gestureArray!
{
    if let tapVar = idxVar as? UITapGestureRecognizer
    {
        if tapVar.numberOfTapsRequired == 2
        {
            tapGesture = tapVar
            NamTxtBoxVal.removeGestureRecognizer(tapGesture)
        }
    }
}

let doubleTap = UITapGestureRecognizer(target: self, action: #selector(namFnc(_:)))
doubleTap.numberOfTapsRequired = 2
doubleTap.delegate = self
tapGesture.requireGestureRecognizerToFail(doubleTap)
NamTxtBoxVal.addGestureRecognizer(doubleTap)

I've also tried:

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool
{

    return false
}
Blue
  • 22,608
  • 7
  • 62
  • 92
Sujay U N
  • 4,974
  • 11
  • 52
  • 88

1 Answers1

1

The only way I know of for you to do this is to

  1. put a UIView behind the UITextField
  2. set the textField's userInteractionEnabled = false
  3. add the double tap gesture to the UIView

This will allow you to register a double tap on the TextField area and not popup any keyboard or enter editing mode.

Not sure what you plan on doing with the textField after double tap but you should be able to handle most stuff programmatically at this point.

Code for this is:

class ViewController: UIViewController {
    @IBOutlet weak var myViewBehindMyTextField: UIView!
    @IBOutlet weak var myTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.myTextFieldTapped(_:)))
        tapGesture.numberOfTapsRequired = 2
        myViewBehindMyTextField.addGestureRecognizer(tapGesture)
    }

    func myTextFieldTapped(sender: UITapGestureRecognizer) {
        print("Double tapped on textField")
    }
}
Travis M.
  • 10,930
  • 1
  • 56
  • 72
  • In ur case, TextField editing on single tap wil go away, which i need. – Sujay U N Jul 22 '16 at 07:02
  • Oh, didn't know you needed it on single tap. Sorry. In that case, I'm not sure how to perform this without the keyboard coming up and disappearing quickly. – Travis M. Jul 22 '16 at 14:57
  • One idea @SujayUN is to put a clearColor UIView above the UITextField. Then have the UIView only pass taps to the UITextField when it's a single tap and have the UIView handle double taps accordingly. – Travis M. Jul 22 '16 at 21:08
  • I also hav pan gesture to move the text feild around the screen, So it becomes difficult handle both on move – Sujay U N Jul 22 '16 at 21:19