How to activate, put the focus on UITextField and at the right time remove, hiding the keyboard? How is the concept of First Responder related to this?
1 answer
How to implement?
Suppose you have a UITextField *textField , then you can move the focus to it and open the keyboard like this:
[textField becomeFirstResponder]; And remove the focus and hide the keyboard like this:
[textField resignFirstResponder]; If you need to handle pressing the Return button on the keyboard, then the controller will need to implement the UITextFieldDelegate protocol and set the controller as a delegate to the text field. Then pressing the button can be processed in this way:
- (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } How it works?
iOS applications receive events that are handled by the appropriate Responder responders . These are objects of the UIResponder classes from UIResponder , most of the controllers and interface elements are inherited from it.
To avoid confusion, all responders are always arranged in a sequence called the Responder chain . At the same time, the very first of them can be highlighted visually, showing the focus on itself, like a UITextField with backlight and an open keyboard. But it is not necessary: ​​after calling resignFirstResponder , the controller becomes the first responder, and it does not visually manifest.
For example, in the player when implementing the "shake to shuffle" feature (shake the smartphone to shuffle the playlist), the view controller acts as the first responder, which intercepts the corresponding event and edits the playlist.
Learn more about this topic here: Understanding Event Handling, Responders, and the Responder Chain .