How to remove focus from UITextField?

Viewed 17101

I have seen this question asked million times everywhere, but there's no single answer that has been working for me.

I need to remove focus from a UITextField. That means I need the cursor to go away (and the keyboard dismissed).

The solution I've seen on the internet is either [textfield resignFirstResponder] or [textfield endEditing:YES], which is able to hide the keyboard, but does not remove focus from UITextField (i.e. the cursor still blinking happily inside the UITextField, although the keyboard is dismissed).

The thing with this is I need to get event when the user tap into the UITextField and the event didBeginEditing is fired. I'm doing something each time that event is fired, or more generally, each time the user tap on the UITextField. But if the focus isn't removed entirely from the UITextField, the event can't be fired again even after I called resignFirstResponder or endEditing:YES.

How can I achieve this? Thanks.

4 Answers

If someone is still facing the issue, the cursor remains if resignFirstResponder() is not called from main queue.

So you just need to:

DispatchQueue.main.async {
  textView.resignFirstResponder()
}

Related