Reputation: 2068
I have a UITextView
and some code in my view controller which dismisses the keyboard when the Done button on the keyboard is pressed, or when tapping outside of the text view. So the user can enter some text into the text view, dismiss the keyboard, then tap in the text view again to re-summon the keyboard.
When I select some text and then dismiss the keyboard, the highlighting over the selected text goes away as expected. But for some reason, if I tap the text that was previously highlighted, the keyboard does not appear and the cursor does not insert into the text view to begin editing, which is the expected behavior.
What could be preventing the text view from recognizing a single tap after the text is highlighted and then the keyboard is dismissed? Note that in this situation, the text view will recognize a double tap or long press gesture, just not a single tap.
Upvotes: 0
Views: 1884
Reputation: 2068
I figured out what the problem is. But I could not find any other question that addresses this specific situation, so I'm answering my own question here in case it may help other people who run into this same issue.
The problem is that when you dismiss the keyboard while you have selected text, although the highlighting on the selected text appears to go away, the system seems to think that the text is still selected and seems to be waiting for some other input. So it does not recognize the usual single tap gesture to begin editing.
What I did is in my view controller where I have the code to dismiss the keyboard, I put textView.selectedTextRange = nil
before dismissing the keyboard. This makes sure there is no selected text in the text view. After that it is safe to dismiss the keyboard.
Here are the two methods I use to dismiss the keyboard, with this line added.
// Dismiss keyboard when touching outside the text view.
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
textView.selectedTextRange = nil // ensures no text is selected, avoiding an issue which prevented single-tapping on the text after keyboard dismisses
view.endEditing(true) // dismisses keyboard
}
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
// Dismiss keyboard when return key is pressed.
if text == "\n" {
textView.selectedTextRange = nil // ensures no text is selected, avoiding an issue which prevented single-tapping on the text after keyboard dismisses
textView.resignFirstResponder() // dismisses keyboard
return false
}
}
Upvotes: 4