Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the currently active UITextField/UITextView and resignFirstResponder?

Is it possible to get the currently active UITextField or UITextView in a UIView, so I can hide the keyboard with [text resignFirstResponder];?

like image 523
Tyilo Avatar asked Jan 22 '12 05:01

Tyilo


2 Answers

As of iOS 2.0 and later, there is an easy way to dismiss the keyboard without having to track the currently active control, or iterating through all the available controls, or using a UITextFieldDelegate.

[self.view endEditing:YES]

From the docs:

endEditing:

Causes the view (or one of its embedded text fields) to resign the first responder status.

- (BOOL)endEditing:(BOOL)force

Parameters
force
Specify YES to force the first responder to resign, regardless of whether it wants to do so.

Return Value
YES if the view resigned the first responder status or NO if it did not.

Discussion
This method looks at the current view and its subview hierarchy for the text field that is currently the first responder. If it finds one, it asks that text field to resign as first responder. If the force parameter is set to YES, the text field is never even asked; it is forced to resign.

like image 126
memmons Avatar answered Oct 07 '22 00:10

memmons


There is no way to directly get what object is the current first responder (that I know of, at least) without testing them individually. What you can do is to create a method containing all subviews which could conceivably be the active first responder, as follows:

- (void)dismissKeyboard {
    if (myTextField1.isFirstResponder) {
        [myTextField1 resignFirstResponder];
    }
    else if (myTextField2.isFirstResponder) {
        [myTextField2 resignFirstResponder];
    }
    else if (myTextField3.isFirstResponder) {
        [myTextField3 resignFirstResponder];
    }
    else if (myTextField4.isFirstResponder) {
        [myTextField4 resignFirstResponder];
    }
}

In reality, though, I tend to do it this way, without first testing whether a particular UIView is the current first responder, and don't think there is any appreciable performance hit/issue (that I've noticed anyway):

- (void)dismissKeyboard {
    //Send resignFirstResponder message to all possible first responders...
    [myTextField1 resignFirstResponder];
    [myTextField2 resignFirstResponder];
    [myTextField3 resignFirstResponder];
    [myTextField4 resignFirstResponder];
}

Hope that helps...

like image 45
Ashwin Avatar answered Oct 06 '22 23:10

Ashwin