Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dismiss number pad keyboard by tapping anywhere

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! :)

like image 838
jsanmtosj Avatar asked Aug 09 '11 03:08

jsanmtosj


People also ask

How do you dismiss a keyboard in tap Swift?

Via Tap Gesture This is the quickest way to implement keyboard dismissal. Just set a Tap gesture on the main View and hook that gesture with a function which calls view. endEditing . Causes the view (or one of its embedded text fields) to resign the first responder status.

How do I dismiss the keyboard for a textfield?

If you're supporting only iOS 15 and later, you can activate and dismiss the keyboard for a text field by focusing and unfocusing it. In its simplest form, this is done using the @FocusState property wrapper and the focusable() modifier – the first stores a Boolean that tracks whether the second is currently focused.


9 Answers

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.

like image 177
Filip Radelic Avatar answered Oct 04 '22 18:10

Filip Radelic


Try this method,

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

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

like image 37
Gajendra K Chauhan Avatar answered Oct 04 '22 17:10

Gajendra K Chauhan


For Swift Use Below Code

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

Check out latest update on following Link

like image 32
abdul sathar Avatar answered Oct 04 '22 17:10

abdul sathar


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.

like image 22
rptwsthi Avatar answered Oct 04 '22 18:10

rptwsthi


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.

like image 37
mbm29414 Avatar answered Oct 04 '22 18:10

mbm29414


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

like image 37
SimplGy Avatar answered Oct 04 '22 18:10

SimplGy


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!

like image 24
Vignesh Avatar answered Oct 04 '22 18:10

Vignesh


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) 
    }
    
like image 40
Oleksii Radetskyi Avatar answered Oct 04 '22 18:10

Oleksii Radetskyi


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.

like image 35
Hadi Avatar answered Oct 04 '22 18:10

Hadi