Is it possible to get the currently active UITextField or UITextView in a UIView, so I can hide the keyboard with [text resignFirstResponder];
?
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
)forceParameters
force
SpecifyYES
to force the first responder to resign, regardless of whether it wants to do so.
Return ValueYES
if the view resigned the first responder status orNO
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 toYES
, the text field is never even asked; it is forced to resign.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With