7

I am using a custom inputView for some textfield, however when i call resignFirstResponder on the textfield, the custom input view does not dismiss...any suggestions?

UITextField *f=[[UITextfield alloc] init];
 UIView *view=[[UIView alloc] initWithFrame..];
   [f setInputView:view]; //random example of how to set a textfields input view to a custom view

After some research, this issue only occurs when working with a viewController thats presented in a modal view...it works ok otherwise...

Thanks

-Daniel

Daniel
  • 22,363
  • 9
  • 64
  • 71
  • by custom text field, you mean you have an object of `UITextField`? Can you post some code? – Anurag Feb 19 '11 at 22:38
  • i mean the inputView property of a UITextfield, check out the snippet of code – Daniel Feb 19 '11 at 22:56
  • Are you still having problems with this? Do you have code of where you are calling resignFirstResponder? Because that should be working – Dan F Jun 14 '11 at 13:57

2 Answers2

7

Instead of calling resignFirstResponder, you should call endEditing: on the view itself or any of its superviews. endEditing: will search all subviews for any view that has first responder status, and ask it to resign.

endEditing: takes a boolean flag as a parameter. If set, it will force the first responder to resign; otherwise, you can allow it to keep focus (if input is invalid, for example). For a UITextField, this is determined by the delegate's shouldEndEditing: method.

In general, a good pattern to use is:

- (void)saveAction:(id)sender
{
    if ([self.view endEditing:NO]) {
        NSString *text = self.textField.text;
        // save text, login, do whatever
    } else {
        // show an alert (or rely on whatever refused to resign to inform the user why)
    }
}
benzado
  • 82,288
  • 22
  • 110
  • 138
  • 1
    this doesn't work for me. It seems to work correctly if the view is just part of the normal window, but if it's in a modal window, the keyboard doesn't go away.. Any ideas? – Eduardo Scoz Mar 21 '12 at 17:22
  • 1
    You must call `endEditing:` on a view that is the parent of the first responder view. It's hard to say exactly what will work without knowing your view hierarchy, but you can try `self.view.window` or `[[UIApplication sharedApplication] keyWindow]`. – benzado Mar 21 '12 at 17:41
  • cool, I'll try the window one. I'm calling it on a parent for sure, but it doesn't seem to work, thanks! – Eduardo Scoz Mar 21 '12 at 18:08
4

If you use a modal view, make make sure to enable automatic keyboard dismissal. Add this code to your view controller:

- (BOOL)disablesAutomaticKeyboardDismissal
{
    return NO;
}
freytag
  • 4,769
  • 2
  • 27
  • 32
  • For anyone who chances on to this question: This answer is the correct solution and not the one about calling endEditing. See similar Q&A here: http://stackoverflow.com/questions/3372333/ipad-keyboard-will-not-dismiss-if-modal-view-controller-presentation-style-is-ui – septerr Feb 05 '14 at 05:06