About the author

Related Articles

32 Comments

  1. 1
    lwdthe1@email.null'

    lwdthe1

    For those struggling with this in Swift. This is the accepted answer by Jensen2k but in Swift.

    Swift 2.3

        override func viewDidLoad() {
            //.....
    
            let viewTapGestureRec = UITapGestureRecognizer(target: self, action: #selector(handleViewTap(_:)))
            //this line is important
            viewTapGestureRec.cancelsTouchesInView = false
            self.view.addGestureRecognizer(viewTapGestureRec)
    
             //.....
        }
    
        func handleViewTap(recognizer: UIGestureRecognizer) {
            myTextField.resignFirstResponder()
        }
    
    Reply
  2. 2
    seggy@email.null'

    seggy

    • Set text fields delegate in view did load:

      override func viewDidLoad() 
      {
        super.viewDidLoad()
        self.userText.delegate = self
      }
      
    • Add this Function:

      func textFieldShouldReturn(userText: UITextField!) -> Bool 
      {
       userText.resignFirstResponder()
       return true;
      }
      
    Reply
  3. 3
    Nirzar

    Nirzar Gandhi

    You can use UITapGestureRecongnizer method for dismissing keyboard by clicking outside of UITextField. By using this method whenever user will click outside of UITextField then keyboard will get dismiss. Below is the code snippet for using it.

     UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                       initWithTarget:self
                                       action:@selector(dismissk)];
    
        [self.view addGestureRecognizer:tap];
    
    
    //Method
    - (void) dismissk
    {
        [abctextfield resignFirstResponder];
        [deftextfield resignFirstResponder];
    
    }
    
    Reply
  4. 4
    Ravi@email.null'

    Ravi

    In this case, there can be use ScrollView and added to TextField in ScrollView and I want Tap the ScrollView and View then Dismiss the Keyboard. I tried to create sample code just in case. Like this,

    import UIKit
    
    class ViewController: UIViewController {
    
        @IBOutlet weak var scrollView: UIScrollView!
        @IBOutlet weak var textField: UITextField!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.tap(_:)))
            view.addGestureRecognizer(tapGesture)
            // Do any additional setup after loading the view, typically from a nib.
        }
        func tap(gesture: UITapGestureRecognizer) {
            textField.resignFirstResponder()
        }
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    }
    

    Your Storyboard Look at that Just Like.

    enter image description here

    Reply
  5. 5
    Syed

    Syed Asad Ali

    Swift version of @Jensen2k’s answer:

    let gestureRecognizer : UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: "dismissKeyboard")
    self.addGestureRecognizer(gestureRecognizer)
    
    func dismissKeyboard() {
        aTextField.resignFristResponder()
    }
    

    One liner

    self.view.addTapGesture(UITapGestureRecognizer.init(target: self, action: "endEditing:"))
    
    Reply
  6. 6
    phani

    phani sai

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    
        if let touch = touches.first{
         view.endEditing(true)
    
         }
    }
    
    Reply
  7. 7
    Maggie

    Maggie Phillips

    This must be the easiest way to hide your keyboard by touching outside :

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

    (from How to dismiss keyboard when user tap other area outside textfield?)

    Reply
  8. 8
    Hiren@email.null'

    Hiren

    You can create category for the UiView and override the touchesBegan meathod as follows.

    It is working fine for me.And it is centralize solution for this problem.

    #import "UIView+Keyboard.h"
    @implementation UIView(Keyboard)
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        [self.window endEditing:true];
        [super touchesBegan:touches withEvent:event];
    }
    @end
    
    Reply
  9. 9
    Chris

    Chris Halcrow

    You can do this using the Storyboard in XCode 6 and above:

    Create the action to hide the keyboard

    Add this to the header file of the class used by your ViewController:

    @interface TimeDelayViewController : UIViewController <UITextFieldDelegate>
    
    - (IBAction)dissmissKeyboardOnTap:(id)sender;
    
    @end
    

    Then add this to the implementation file of the same ViewController:

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

    This will now be one of the ‘Received Actions’ for your storyboard scene (i.e. ViewController):

    enter image description here

    Hook up the action to the user event

    Now you need to hook up this action to the user gesture of touching off the keyboard.

    Important – You need to convert the ‘UIView’ that’s contained in your storyboard to a UIControl, so it can receive events. Select the view from your View Controller Scene hierarchy:

    enter image description here

    …and change its class:

    enter image description here

    Now drag from the small circle next to the ‘received action’ for your scene, onto an ’empty’ part of your scene (actually you’re dragging the ‘Received Action’ to the UIControl). You’ll be shown a selection of events that you can hook up your action to:

    enter image description here

    Select the ‘touch up inside’ option. You’ve now hooked the IBAction you created to a user action of touching off the keyboard. When the user taps off the keyboard, it will now be hidden.

    (NOTE: To hook the action to the event, you can also drag from the received action directly onto the UIControl in your View Controllers hierarchy. It’s displayed as ‘Control’ in the hierarchy.)

    Reply
  10. 10
    Amit

    Amit Shelgaonkar

    just use this code in your .m file it will resign the textfield when user tap outside of the textfield.

     -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
      [textfield resignFirstResponder];
     }
    
    Reply
  11. 11
    Sudhin

    Sudhin Davis

    One of the most easiest and shortest way is to add this code to your viewDidLoad

    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc]
                                         initWithTarget:self.view
                                         action:@selector(endEditing:)]];
    
    Reply
  12. 12
    Joey

    Joey Tribbiani

    Check this, this would be the easiest way to do that,

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
          [self.view endEditing:YES];// this will do the trick
    }
    

    Or

    This library will handle including scrollbar auto scrolling, tap space to hide the keyboard, etc…

    https://github.com/michaeltyson/TPKeyboardAvoiding

    Reply
  13. 13
    eduludi@email.null'

    eduludi

    This is a good generic solution:

    Objective-C:

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

    Swift:

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

    Based on @icodebuster solution: http://stackoverflow.com/a/18756253/417652

    Reply
  14. 14
    Joe

    Joe Masilotti

    If the view is embedded at all in a UIScrollView then you can use the following:

    tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;
    

    The former will animate the keyboard off screen when the table view is scrolled and the later will hide the keyboard like the stock Messages app.

    Note that these are are available on iOS 7.0 or above.

    Reply
  15. 15
    skedastik@email.null'

    skedastik

    Plenty of great answers here about using UITapGestureRecognizer–all of which break UITextField‘s clear (X) button. The solution is to suppress the gesture recognizer via its delegate:

    - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
        BOOL touchViewIsButton = [touch.view isKindOfClass:[UIButton class]];
        BOOL touchSuperviewIsTextField = [[touch.view superview] isKindOfClass:[UITextField class]];
        return !(touchViewIsButton && touchSuperviewIsTextField);
    }
    

    It’s not the most robust solution but it works for me.

    Reply
  16. 16
    drewish@email.null'

    drewish

    I mashed up a few answers.

    Use an ivar that gets initialized during viewDidLoad:

    UIGestureRecognizer *tapper;
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        tapper = [[UITapGestureRecognizer alloc]
                    initWithTarget:self action:@selector(handleSingleTap:)];
        tapper.cancelsTouchesInView = NO;
        [self.view addGestureRecognizer:tapper];
    }
    

    Dismiss what ever is currently editing:

    - (void)handleSingleTap:(UITapGestureRecognizer *) sender
    {
        [self.view endEditing:YES];
    }
    
    Reply
  17. 17
    mtorre@email.null'

    mtorre

    I used Barry example for my new development. It worked great! but i had to include a slightly change, required to dismiss the keyboard only for the textfield being edited.

    So, I added to Barry example the following:

    - (void) textFieldDidBeginEditing:(UITextField *)textField
    {
        _textBeingEdited = textField;
    }
    -(void) textFieldDidEndEditing:(UITextField *)textField
    {
        _textBeingEdited = nil;
    }
    

    Also, I changed hideKeyboard method as follows:

    - (IBAction)hideKeyboard:(id)sender
    {
        // Just call resignFirstResponder on all UITextFields and UITextViews in this VC
        // Why? Because it works and checking which one was last active gets messy.
        //UITextField * tf = (UITextField *) sender;
        [_textBeingEdited resignFirstResponder];
    }
    
    Reply
  18. 18
    Qiao

    Qiao Yi

    I see that some people are having issues using the UITapGestureRecognizer method. The easiest way that I’ve accomplished this functionality while still leaving my existing button’s tap behavior intact is adding only one line to @Jensen2k ‘s answer:

    [tap setCancelsTouchesInView:NO];
    

    This allowed my existing buttons to still work without using @Dmitry Sitnikov ‘s method.

    Read about that property here (search for “CancelsTouchesInView”): UIGestureRecognizer Class Reference

    I’m not sure how it would work with scrollbars, as I see some had issues with, but hopefully someone else might run into the same scenario I had.

    Reply
  19. 19
    user1021430@email.null'

    user1021430

    I tried many of the responses here and had no luck. My tap gesture recognizer was always causing my UIButtons to not respond when tapped, even when I set the cancelsTouchesInView property of the gesture recognizer to NO.

    This is what eventually solved the issue:

    Have an ivar:

    UITapGestureRecognizer *_keyboardDismissGestureRecognizer;
    

    When a text field begins editing, set the gesture recognizer:

    - (void) textFieldDidBeginEditing:(UITextField *)textField
    {
        if(_keyboardDismissGestureRecognizer == nil)
        {
            _keyboardDismissGestureRecognizer = [[[UITapGestureRecognizer alloc]
                                           initWithTarget:self
                                           action:@selector(dismissKeyboard)] autorelease];
            _keyboardDismissGestureRecognizer.cancelsTouchesInView = NO;
    
            [self.view addGestureRecognizer:_keyboardDismissGestureRecognizer];
        }
    }
    

    Then the trick is in how you set up the dismissKeyboard method:

    - (void) dismissKeyboard
    {
        [self performSelector:@selector(dismissKeyboardSelector) withObject:nil afterDelay:0.01];
    }
    
    - (void) dismissKeyboardSelector
    {
        [self.view endEditing:YES];
    
        [self.view removeGestureRecognizer:_keyboardDismissGestureRecognizer];
        _keyboardDismissGestureRecognizer = nil;
    }
    

    I guess there’s just something about getting the dismissKeyboardSelector execution out of the touch handling execution stack…

    Reply
  20. 20
    Barry@email.null'

    Barry

    This works

    In this example, aTextField is the only UITextField…. If there are others or UITextViews, there’s a tiny bit more to do.

    // YourViewController.h
    // ...
    @interface YourViewController : UIViewController /* some subclass of UIViewController */ <UITextFieldDelegate> // <-- add this protocol
    // ...
    @end
    
    // YourViewController.m
    
    @interface YourViewController ()
    @property (nonatomic, strong, readonly) UITapGestureRecognizer *singleTapRecognizer;
    @end
    // ...
    
    @implementation
    @synthesize singleTapRecognizer = _singleTapRecognizer;
    // ...
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // your other init code here
        [self.view addGestureRecognizer:self.singleTapRecognizer];
    
    {
    
    - (UITapGestureRecognizer *)singleTapRecognizer
    {
        if (nil == _singleTapRecognizer) {
            _singleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapToDismissKeyboard:)];
            _singleTapRecognizer.cancelsTouchesInView = NO; // absolutely required, otherwise "tap" eats events.
        }
        return _singleTapRecognizer;
    }
    
    // Something inside this VC's view was tapped (except the navbar/toolbar)
    - (void)singleTapToDismissKeyboard:(UITapGestureRecognizer *)sender
    {
        NSLog(@"singleTap");
        [self hideKeyboard:sender];
    }
    
    // When the "Return" key is pressed on the on-screen keyboard, hide the keyboard.
    // for protocol UITextFieldDelegate
    - (BOOL)textFieldShouldReturn:(UITextField*)textField
    {
        NSLog(@"Return pressed");
        [self hideKeyboard:textField];
        return YES;
    }
    
    - (IBAction)hideKeyboard:(id)sender
    {
        // Just call resignFirstResponder on all UITextFields and UITextViews in this VC
        // Why? Because it works and checking which one was last active gets messy.
        [aTextField resignFirstResponder];
        NSLog(@"keyboard hidden");
    }
    
    Reply
  21. 21
    rptwsthi@email.null'

    rptwsthi

    If I got you right you want to resign keyboard wile tapping on outSide of textfield but you don’t have reference of your textfield.

    Try this;

    • Take global textField, lets call it reftextField
    • Now in textFieldDidBeginEditing set referenced text field to

      - (void) textFieldDidBeginEditing:(UITextField *)textField{
          reftextField = textField;
      }
      
    • Now you can happily use on any button clock, (adding a transparent button on begin editing recomended)

      - (void)dismissKeyboard {
            [reftextField resignFirstResponder];
      }
      
    • Or for resigning done button try this.

      //for resigning on done button    
      - (BOOL) textFieldShouldReturn:(UITextField *)textField{
          [textField resignFirstResponder];
          return YES;
      }
      
    Reply
  22. 22
    Jensen2k@email.null'

    Jensen2k

    You’ll need to add an UITapGestureRecogniser and assign it to the view, and then call resign first responder on the textfield on it’s selector.

    The code:

    In viewDidLoad

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] 
                                           initWithTarget:self
                                           action:@selector(dismissKeyboard)];
    
    [self.view addGestureRecognizer:tap];
    

    In dismissKeyboard:

    -(void)dismissKeyboard {
           [aTextField resignFirstResponder];
    }
    

    (Where aTextField is the textfield that is responsible for the keyboard)

    Reply
  23. 23
    Enzo

    Enzo Tran

    I think the easiest (and best) way to do this is to subclass your global view and use hitTest:withEvent method to listen to any touch. Touches on keyboard aren’t registered, so hitTest:withEvent is only called when you touch/scroll/swipe/pinch… somewhere else, then call [self endEditing:YES].

    This is better than using touchesBegan because touchesBegan are not called if you click on a button on top of the view. It is better than UITapGestureRecognizer which can’t recognize a scrolling gesture for example. It is also better than using a dim screen because in a complexe and dynamic user interface, you can’t put dim screen every where. Moreover, it doesn’t block other actions, you don’t need to tap twice to select a button outside (like in the case of a UIPopover).

    Also, it’s better than calling [textField resignFirstResponder], because you may have many text fields on screen, so this works for all of them.

    Reply
  24. 24
    Mr

    Mr H

    How about this: I know this is an old post. It might help someone :)

    -(void)touchesEnded: (NSSet *) touches withEvent: (UIEvent *) event {   
        NSArray *subviews = [self.view subviews];
        for (id objects in subviews) {
            if ([objects isKindOfClass:[UITextField class]]) {
                UITextField *theTextField = objects;
                if ([objects isFirstResponder]) {
                    [theTextField resignFirstResponder];
                }
            } 
        }
    }
    
    Reply
  25. 25
    Ke

    Ke Sun

    Send message resignFirstResponder to the textfiled that put it there. Please see this post for more information.

    Reply
  26. 26
    Gaurav

    Gaurav Gilani

    - (void)viewDidLoad
    {
        [super viewDidLoad]; 
    
    UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc]
                                                              initWithTarget:self
                                                              action:@selector(handleSingleTap:)];
        [singleTapGestureRecognizer setNumberOfTapsRequired:1];
        [singleTapGestureRecognizer requireGestureRecognizerToFail:singleTapGestureRecognizer];
    
        [self.view addGestureRecognizer:singleTapGestureRecognizer];
    }
    
    - (void)handleSingleTap:(UITapGestureRecognizer *)recognizer
    {
        [self.view endEditing:YES];
        [textField resignFirstResponder];
        [scrollView setContentOffset:CGPointMake(0, -40) animated:YES];
    
    }
    
    Reply
  27. 27
    Derek

    Derek Dawson

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        super.view.endEditing(true)
        super.touchesBegan(touches, withEvent: event)
    }
    
    Reply
  28. 28
    John

    John Riselvato

    Just to add to the list here my version of how to dismiss a keyboard on outside touch.

    viewDidLoad:

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [self.view addGestureRecognizer:singleTap];
    

    Anywhere:

    -(void)handleSingleTap:(UITapGestureRecognizer *)sender{
        [textFieldName resignFirstResponder];
        puts("Dismissed the keyboard");
    }
    
    Reply
  29. 29
    Rob@email.null'

    Rob

    Swift version, this works in combination with other elements (like a UIButton or another UITextField):

    override func viewDidLoad() {
        super.viewDidLoad()
    
        let tapper = UITapGestureRecognizer(target: view, action:#selector(endEditing))
        tapper.cancelsTouchesInView = false
        view.addGestureRecognizer(tapper)
    }
    
    Reply
  30. 30
    Dmitry

    Dmitry Sitnikov

    It is better to make your UIView an instance of UIControl (in interface builder) and then connect their “Touch Up Inside” event to dismissKeyboard method. This IBAction method will look like:

    - (IBAction)dismissKeyboard:(id)sender {
        [aTextBox resignFirstResponder];
    }
    
    Reply
  31. 31
    Macondo2Seattle@email.null'

    Macondo2Seattle

    So I just had to solve this very problem, and none of the previous answers worked for me out of the box. My situation: a UISearchBar, plus a number of other controls on the screen. I want for a tap outside of the search bar to dismiss the keyboard, but not propagate to any of the other controls. When the keyboard is hidden, I want all the controls to work.

    What I did:

    1) Implement a custom touch handler in my view controller.

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
    {
        if searchBar.isFirstResponder()
        {
            // This causes the first responder, whoever it is, to resign first responder, and hide the keyboard.
            // We also "eat" the touch here and not allow it to propagate further.
            view.endEditing(true)
        }
        else
        {
            // OK to propagate the touch
            super.touchesBegan(touches, withEvent: event)
        }
    }
    

    2) Added a couple of delegate methods (mine are for the UISearchBar, but there are similar ones for UITextField). controlContainerView in the code below is a UIView that has a bunch of buttons in it. Remember that setting userInteractionEnabled on a superview disables all its subviews.

     func searchBarTextDidBeginEditing(searchBar: UISearchBar)
     {
         controlContainerView.userInteractionEnabled = false
         someButton.userInteractionEnabled = false
     }
    
     func searchBarTextDidEndEditing(searchBar: UISearchBar)
     {
         searchBar.resignFirstResponder()
    
        // Done editing: enable the other controls again.
    
        controlContainerView.userInteractionEnabled = false
        someButton.userInteractionEnabled = false
    }
    
    Reply
  32. 32
    Aashish

    Aashish Tamsya

    Add this code in your ViewController.m file :

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

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2017 SolutionMmyself.com