IPad dismiss Keyboard without knowing which Textfield opened it
Is there a way to do a general resignFirstResponder
to hide the keyboard regardless of what textfield/view/etc calls it?
Reason is I have a lot of textfields on my view and don't want to have to resignFirstResponder
for all textfields to hide the keyboard. Jus开发者_开发百科t want a general
[self resignFirstResponder]
.
Any ideas?
Thanks in advance
I know that this has already been marked as answered, but for those that run into this like I did you can just use the following method on the view that contains the textfields.
- (BOOL)endEditing:(BOOL)force
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. UIView Documentation
[self.view endEditing:YES];
it will hide keyboard when we click on view.
You can dismiss the keyboard without any reference to UITextfield / UITextView with help of below code:
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
this will dismiss the keyboard globally without the reference.
hope this will help you.
The easiest way to do this is to have a method for whenever you want to dismiss the keyboard that looks like this:
-(void)dismissKeyboard {
[firstField becomeFirstResponder];
[firstField resignFirstResponder];
}
You can check these questions:
- Is it possible to make the iPhone keyboard invisible / remove it without resigning first responder?
- Hide Input Keyboard on iPhone Without Knowing First Responder?
In summary: You can call becomeFirstResponder on some other thing that you choose. It could be a UIViewController or a UIView. I had a similar problem before, I needed to make my keyboard go away when I was pushing my view controller back to its caller, without knowing which textfield was the first responder. Then, on viewWillAppear of my view controller which I was returning back, I called [self becomeFirstResponder] and the keyboard of the pushed view was gone. Because this made whichever text field was it loose being the first responder
In my own app when I had more than one text field and would like to make the keyboard go away regardless which of the fields called it, I would just wrote a method and let each and every of them resignFirstResponder
.
I assume that as a programmer, you should have the clear knowledge how many text fields are on your view controller and how you can access them, otherwise it'll get messed up and you app won't look good... :-P
精彩评论