iosobjective-cuitextfield

How to remove focus from UITextField?


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.


Solution

  • I had the same problem ages ago.

    I had a screen containing a UITextField, and some other controls, some of which were appearing under the onscreen keyboard (yes, I know now I should've used constraints to make sure the onscreen UIView fitted the visible part of the screen).

    The problem in my case was that on a Modal screen, once the onscreen keyboard appears, you can never get rid of it, even if you try using resignFirstResponder. In its wisdom, Apple has deliberately designed it this way, to stop the user being annoyed by the keyboard appearing, and disappearing. Uh-huh.

    My solution was simple:

    Make your UITextField disabled. Even if it's just for a fraction of a second, then you re-enable it.

    This'll make the onscreen keyboard nicely slide away.