ntaj
ntaj

Reputation: 311

UITextField not responding to tap

I'm trying to highlight the text in my UITextField when it is tapped by the user. The behaviour works as expected the first time I tap into the field. Once I tap out (resign first responder) and then tap back in, the text field does not regain focus unless I double-tap or long press the text field.

Here's my code.

override func viewDidLoad() { 
    textField.delegate = self

    // tap gesture to resign first responder 
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard(gestureRecognizer:)))
    self.view.addGestureRecognizer(tapGesture)
}

@objc func dismissKeyboard(gestureRecognizer: UITapGestureRecognizer) {
    textField.resignFirstResponder()
}


func textFieldDidBeginEditing(_ textField: UITextField) {

    // if I comment out this line or replace with a print statement, the text field regains focus on a single tap as expected        
    textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument)
}

If I remove the code in textFieldDidBeginEditing that is responsible for selecting all text, the text field successfully regains focus on a single tap (but obviously does not highlight the text).

I tried placing a print statement in textFieldDidBeginEditing and it doesn't get called until the double-tap or long-press when the textField.selectedRange = ... line is present. However, if I comment this line, then the print statement executes every time I tap into the text field.

Upvotes: 3

Views: 1667

Answers (1)

matt
matt

Reputation: 534925

I fixed it like this:

self.textField.resignFirstResponder()
self.textField.selectedTextRange = nil

Upvotes: 1

Related Questions