I\'d like to know the simplest code to dismiss the number pad keyboard when tapping anywhere outside the number pad. It\'s a simple application to input a number inside a te
I tried implementing some of the solutions here and found that there were some issues with them. Notably, My UIView
contains a UIScrollView
, which appears to intercept touches.
When that failed, I considered that "tapping anywhere" is a little bit of an unspecified behavior, requiring the user to guess how to dismiss the keyboard instead of giving them clear guidance.
Also, I have a "Return" or "Done" button on every other keyboard I show in the app, so I was determined to give the user an easy, intuitive, clearly-specified way to dismiss the keyboard with a Number Pad that was in line with the other keyboard dismissal mechanisms in use.
I realize that this isn't what the OP is specifically requesting, but I believe it to be a better solution than the "tap anywhere" request (and it's easy to implement!).
The following code is called as part of -viewDidLoad
in my UIViewController
.
// My app is restricted to portrait-only, so the following works
UIToolbar *numberPadAccessoryInputView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44.0f)];
// My app-wide tint color is a gold-ish color, so darkGray contrasts nicely
numberPadAccessoryInputView.barTintColor = [UIColor darkGrayColor];
// A basic "Done" button, that calls [self.textField resignFirstResponder]
UIBarButtonItem *numberPadDoneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self.textField action:@selector(resignFirstResponder)];
// It's the only item in the UIToolbar's items array
numberPadAccessoryInputView.items = @[numberPadDoneButton];
// In case the background of the view is similar to [UIColor darkGrayColor], this
// is put as a contrasting edge line at the top of the UIToolbar
UIView *topBorderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, numberPadAccessoryInputView.frame.size.width, 1.0f)];
topBorderView.backgroundColor = [UIColor whiteColor];
[numberPadAccessoryInputView addSubview:topBorderView];
// Make it so that this UITextField shows the UIToolbar
self.textField.inputAccessoryView = numberPadAccessoryInputView;
With that, there's a nice, pretty, intuitive control added to the top of the keyboard that clearly indicates how the user should proceed when they are finished with their text entry.
I still believe Apple should provide a "Done" button for this keyboard (like the link posted by Janak Nirmal), but this is the most elegant non-Apple solution to me.