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
Just make a simple function like this one..
-(IBAction)hideKeyboard:(id)Sender
{
[_textValue resignFirstResponder];
}
now go to ur nib file and connect this function with the textfield with didEndOnExit
and you are good to go. Now when u will click outside ur textfield the keyboard will hide itself.
You must use UITapGestureRecognizer to achieve this.
UITapGestureRecognizer *tapToDismiss = [[UITapGestureRecognizer alloc]initWithTarget: self action: @selector (dismissNumberKeyBoard:)];
Then in your dismissNumberKeyboard method,
-(Void)dismissNumberKeyboard : (id)sender {
[yourTextField resignFirstResponder];
}
Happy coding!
Normally, when the user touches on 'Cancel' button, I use this to dismiss Keyboard -
- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{
NSLog(@"cancel clicked");
[searchBar resignFirstResponder]; // dismiss keyboard
return;
}
If you want to do this for when the user touches anywhere outside the keyboard area, then you need to implement touchesEnded
& put this code there -
/* Delegate for when touch ends. */
-(void)touchesEnded:(NSSet *)touches
withEvent:(UIEvent *)event
{
[searchBar resignFirstResponder];
}
I myself have not tried this, but I recon this should do the trick...
For Swift Use Below Code
override func touchesBegan(touches: NSSet, withEvent event: UIEvent)
{
textFiled.resignFirstResponder()
}
Check out latest update on following Link
Declaring the text field as instance variable or property if it isn't already and implementing a simple method like this:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[textField resignFirstResponder];
}
will do just fine.
If you've made a custom number pad or other popover, another solution would be to use a gesture recognizer in the init of your UIView like this:
tapper = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
tapper.cancelsTouchesInView = NO;
[self addGestureRecognizer:tapper];
_yourViewController = [[CustomViewController alloc] init];
_yourPopoverController = [[UIPopoverController alloc] initWithContentViewController:_yourViewController];
_yourPopoverController.popoverContentSize = CGSizeMake(550, 300);
_yourViewController.delegate = self;
And have the handleSingleTap dismiss the popover if visible and dismiss editing:
- (void)handleSingleTap:(UITapGestureRecognizer *) sender
{
if ([_yourPopoverController isPopoverVisible]) {
[_yourPopoverController dismissPopoverAnimated:YES];
}
[self endEditing:YES];
}