53
votes

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 text field and then a user can dismiss the keyboard after the user finishes typing the numbers on the text field. Thanks! :)

16
If you want to put Done button on Numeric button you can follow this link neoos.ch/news/46-development/…Janak Nirmal

16 Answers

85
votes

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.

21
votes

Try this method,

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
   [self.view endEditing:YES];
}

Now tap anywhere and see keyboard will dismiss. :-)

8
votes

For Swift Use Below Code

override func touchesBegan(touches: NSSet, withEvent event: UIEvent)
 {
       textFiled.resignFirstResponder()
 }

Check out latest update on following Link

6
votes

Touching the Background to Close the Keyboard

Go to Xcode if you’re not already there. We need to add one more action to our controller class. Add the following line to your Control_FunViewController.h file:

#import <UIKit/UIKit.h>
@interface Control_FunViewController : UIViewController { 
UITextField *nameField;
UITextField *numberField;
}
 @property (nonatomic, retain) IBOutlet UITextField *nameField; ]
@property (nonatomic, retain) IBOutlet UITextField *numberField; 
- (IBAction)textFieldDoneEditing:(id)sender; 
- (IBAction)backgroundTap:(id)sender; 
@end  

Save the header file; switch over to the implementation file, and add this code, which simply tells both text fields to yield first responder status if they have it. It is perfectly safe to call resignFirstResponder on a control that is not the first responder, so we can safely call it on both text fields without having to check whether either is the first responder.

- (IBAction)backgroundTap:(id)sender { 
[nameField resignFirstResponder]; 
[numberField resignFirstResponder];
}

TIP Save this file, and go back to Interface Builder. We now need to change the underlying class of our nib’s view. If you look at the nib’s main window , you’ll see that there are three icons in that view. The third one, called View, is our nib’s main view that holds all the other controls and views as subviews. Single-click the icon called View, which represents our nib’s container view. Press ␣4 to bring up the identity inspector. This is where we can change the underlying class of any object instance in Interface Builder.

You’ll be switching between header and implementation files a lot as you code. Fortunately, Xcode has a key combination that will switch you between these files quickly. The default key combination is ␣␣␣ (option-command-up arrow), although you can change it to anything you want using Xcode’s preferences.76

The field labeled Class currently says UIView. Change it to read UIControl. All controls that are capable of trig- gering action methods are subclasses of UIControl, so by changing the underlying class, we have just given this view the ability to trigger action methods. You can verify this by pressing ␣2 to bring up the connections inspector.

Drag from the Touch Down event to the File’s Owner icon, and choose the backgroundTap: action. Now, touches anywhere in the view without an active control will trigger our new action method, which will cause the keyboard to retract.

NOTE Save the nib, and let’s go back and try it. Compile and run your application again. This time, the keyboard should disappear not only when the Done button is tapped but also when you click anywhere that’s not an active control, which is the behavior that your user will expect.

4
votes

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.

4
votes

You can implement @mbm's answer really nicely by putting a didSet on the outlet and attaching your inputAccessoryView there:

Swift code:

  @IBOutlet var input: UITextField! { didSet {
    let toolbar = UIToolbar(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 0, height: 44)))
    toolbar.items = [
      UIBarButtonItem(barButtonSystemItem: .done, target: self.input,
        action: #selector(resignFirstResponder))
    ]
    input.inputAccessoryView = toolbar
  }}

In xcode 8 / iOS 10 It ends up looking something like this:

enter image description here

2
votes

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!

2
votes

For swift 3/4 I like this case:

  1. View Controller is subclass for UITextFieldDelegate
  2. In the viewDidLoad function, you have to set yourPhonePadField.delegate = self
  3. And override this function:

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
       self.view.endEditing(true) 
    }
    
1
votes

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.

0
votes

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...

0
votes

I had to implement a similar UX for my UITableView (inside which appears a UITextField). First, add a UITapGestureRecognizer to the tableView. This will begin to catch all the taps that occur from now on.

UITapGestureRecognizer* tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
        [self.tableView addGestureRecognizer:tapGestureRecognizer];
        [tapGestureRecognizer release];

The side-effect is however, that you do not want to dismiss the keyboard when the user taps on the UITextField itself. So, this case has to be distinguished.

The handleTap method implementation looks something like-

/*
 In the text editing mode, listens to all taps occurring on the table view to exit the mode. There are two special cases to consider:
 a) Text field's clear button
 b) Text field
 */
-(void)handleTap:(UITapGestureRecognizer*)tapRecognizer 
{
    if(tapRecognizer.state == UIGestureRecognizerStateEnded) 
    {

            //Figure out where the user tapped
            CGPoint p = [tapRecognizer locationInView:textField];
            CGRect textFieldBounds = textField.bounds;
            CGRect clearButtonBounds = CGRectMake(textFieldBounds.origin.x + textFieldBounds.size.width - 44, textFieldBounds.origin.y, 44, textFieldBounds.size.height); 

            if(CGRectContainsPoint(clearButtonBounds, p))
                textField.text = @"";

            if(CGRectContainsPoint(textFieldBounds, p))
                return;

        [textField resignFirstResponder];
        //remove the tap gesture recognizer that was added.
        for(id element in self.tableView.gestureRecognizers)
        {
        if([element isKindOfClass:[UITapGestureRecognizer class]])
        {
            [self.tableView removeGestureRecognizer:element];
        }
        }
    }
        [self commitNewText];
    }
}

HTH. Mark it as the answer if you like it.

-Akshay

0
votes

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];
}
0
votes

In xcode 5 Use a Tap Gesture Recognizer and declare in the .h with action chose a name and in .m

- (IBAction)backgroundTap:(id)sender {
    [self.view endEditing: YES];
}
0
votes

Lots of answers here but still had to struggle to figure it out using XCode 5. Read this: https://developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/GestureRecognizer_basics/GestureRecognizer_basics.html

Add a Tap Gesture Recognizer to your UIScrollView. Set its delegate to be the viewcontroller.

Add this method:

- (IBAction)tappedSomewhere:(id)sender {
    [self.view endEditing:YES];
}

to your UIScrollView implementation code and associate it to the Tap Gesture Recognizer by control click and dragging to the implementation code.

Worked for me.

0
votes

For Swift, the easiest for dismissing keypad for all text fields by tapping anywhere outside the text field is:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent)
{
    self.view.endEditing(true)
}
0
votes

Swift 5

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
           self.view.endEditing(true)
           return true
 }