Ios Swift Override double tap of UItextField

戏子无情 提交于 2019-12-23 03:04:30

问题


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
}

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


来源:https://stackoverflow.com/questions/38513782/ios-swift-override-double-tap-of-uitextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!