UITapGestureRecognizer on a text field not as expected

孤人 提交于 2019-12-20 03:05:52

问题


In my class I have 11 UITapGestureRecognizers in an array textViewRecognizer attached to 11 out of 100 UITextFields in an array boxArray. When a Textfield is tapped containing a UIGestureRecognizer it runs tappedTextView where I try to get the index of the first responder.

However, due to some weird ordering in how things are executed, the action function only gives me the first responder of the previous first responder to the one that was just tapped.

Also, I have to double tap to even select the text field I was going for! I need to use the tap function and not the text delegates so this has been a real headache.

I have...

    @objc func tappedTextField(_ sender: UITapGestureRecognizer) {
    for i in 0...99 {
        if (boxArray[i]?.isFirstResponder)! {
            if let index = boxArray.index(of: boxArray[i]) {
            print(index)
            break
            }
        }
    }
}

in my viewDidLoad I have

for i in 0...10 {
        textFieldTapRecognizer[i].addTarget(self, action: #selector(self.tappedTextField(_:)))
}

In my class I have

I want to set 11 out of 100 textFields to have this a tap recognizer depending on some conditions (I'm just going to use a regular for loop here)

for i in 0...10 {
         boxArray[i]?.addGestureRecognizer(textFieldTapRecognizer[i])
}
  1. Is there anyway I can get it to give me the actual first responder, after the tap was made?

  2. Is there anyway to go around the double tap to select the text field that has a UITapGesture?

Any help is greatly appreciated.

Edited: properly named functions


回答1:


It sounds like you want to remove the automatic editing behavior on a UITextView. You can grab more control over that with the textViewShouldBeginEditing(_ textView: UITextView) -> Bool UITextViewDelegate method, documented here.

If you return false for that method, this should avoid needing a double tap to get to your gesture recognizer. Depending on your use case, you can then "allow" the tap to go to the text view by returning true for the textView you want to be actually edited.

While I'm not 100% clear on the first responder part of your question, since the textView won't be grabbing first responder if it's not starting it's editing mode, this should address that concern I believe. Good luck!




回答2:


I would add a Tag to my UITextView and set the UITextViewDelegate to my ViewController.

Then I would add the following Delegate method:

func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
    print("Textview tag: ", textView.tag)
    return false
}


来源:https://stackoverflow.com/questions/50177364/uitapgesturerecognizer-on-a-text-field-not-as-expected

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