442

I have been looking all over for this but I can't seem to find it. I know how to dismiss the keyboard using Objective-C but I have no idea how to do that using Swift? Does anyone know?

Sandy
  • 4,714
  • 4
  • 42
  • 69
lagoon
  • 5,747
  • 6
  • 19
  • 28
  • 9
    How are you doing it in Objective-C? It's normally a conversion from one syntax to the other, and rarely a matter of different methods/conventions. – Craig Otis Jun 09 '14 at 18:39
  • You might want to check [this answer](http://stackoverflow.com/questions/39880482/how-to-dismiss-keyboard-when-touching-away-across-the-entire-app/39880997#39880997). – Ahmad F Dec 07 '16 at 01:34

39 Answers39

1383
override func viewDidLoad() {
    super.viewDidLoad()
          
    //Looks for single or multiple taps. 
     let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))

    //Uncomment the line below if you want the tap not not interfere and cancel other interactions.
    //tap.cancelsTouchesInView = false 

    view.addGestureRecognizer(tap)
}

//Calls this function when the tap is recognized.
@objc func dismissKeyboard() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    view.endEditing(true)
}

Here is another way to do this task if you are going to use this functionality in multiple UIViewControllers:

// Put this piece of code anywhere you like
extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false            
        view.addGestureRecognizer(tap)
    }
    
    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
}

Now in every UIViewController, all you have to do is call this function:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround() 
}

This function is included as a standard function in my repo which contains a lot of useful Swift Extensions like this one, check it out: https://github.com/goktugyil/EZSwiftExtensions

spacecash21
  • 1,243
  • 1
  • 16
  • 39
Esqarrouth
  • 35,175
  • 17
  • 147
  • 154
  • This approach adds flexibility and reusability. In case `tableView` isn't part of the app can be substituted by any other `view`. – carlodurso Dec 14 '14 at 13:49
  • @Esq Do I have to add this on each view or in ViewController only. – Eduard Oct 20 '15 at 13:13
  • 1
    View controller only. But if you have multiple viewcontrollers and different screens, you need to do it in each screen. But the main view, should be containing all other views as subviews in that vc. – Esqarrouth Oct 20 '15 at 13:56
  • 1
    This answer didn't work for me but the UITextFieldDelegate answer by @King-Wizard did. – Suragch Oct 29 '15 at 08:56
  • 19
    Since Swift 2 in the first answer, replace this line-> let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(MyViewController.dismissKeyboard)) – Sam Bellerose Mar 29 '16 at 03:56
  • 2
    it breaks tableviewcell's segue on a tableviewcontroller – Utku Dalmaz Apr 01 '16 at 10:39
  • This shouldn't break stuff. Maybe there is something else in your code? – Esqarrouth Apr 01 '16 at 13:51
  • 11
    This is one of the most helpful extensions I have ever come across! Thank you! The only caution I would extend is that this can interfere with `didSelectRowAtIndexPath`. – Clifton Labrum Apr 05 '16 at 06:46
  • @CliftonLabrum Thanks. What kind a precautions do you recommend for this? Please feel to send a pull request if you have some ideas – Esqarrouth Apr 05 '16 at 08:25
  • Messes with tableviews. The answer below by @King-Wizard is money. – 36 By Design Apr 20 '16 at 06:18
  • This answer does not work for me. The UI becomes unresponsive. – RandyTek May 17 '16 at 20:36
  • 1
    I have my TextView in a static tableView which also contains a PickerView and Button, tapping either of the other controls does not trigger the tap gesture action to hide the keyboard. Any ideas? – Paul Popiel Jun 07 '16 at 11:19
  • 1
    This is messing my TableVew, didSelectRowAtIndexPath delegate method is nat called. Any ideas? – Boris Nikolic Jun 08 '16 at 14:21
  • 50
    Just discovered this question and implemented that method. That thing with "didSelectRow" of tableView/UICollectionView not calling literally drove me crazy. The solution is: Simply add this to your extension: `tap.cancelsTouchesInView = false`. That solved it for me at least. Hope this helps somebody – Quantm Jul 28 '16 at 10:27
  • 1
    don't forget to set UITapGestureRecognizer **cancelTouches** to false if your view controller has a **tableView** this will intercept tap and prevent _didSelectRowAtIndexPath_ to be called `tap.cancelsTouchesInView = false` – Dania Delbani Sep 23 '16 at 04:50
  • @Esqarrouth, Can you please edit your answer to include "tap.cancelsTouchesInView = false". Without that, it cancels touches and disables interactions in subviews. – bond Oct 15 '16 at 21:59
  • Works nice except on a table view that has a selectable cell that segues into another view. The tap gets in the way and prevents the segue/cell touch. – Jose Ramirez Jan 29 '17 at 03:10
  • 1
    I implement this method, but if I have tableview that inside the cell I have button, when I tap the button, It hide the keyboard first, and then the button got tapped after tap again. Is there any way to solve this issue? – Jefferson Setiawan Jul 05 '17 at 10:28
  • Best solution! For Swift 4, don't forget to add @objc before func dismissKeyboard() – Gefilte Fish Feb 13 '18 at 12:23
  • I had problem with this extension, for instance i have button on the view and i click on the button, the keyboard will close but the button action will not work properly – Maor May 13 '18 at 16:26
  • All I needed was the `view.endEditing(true)` part for Did End Editing. –  Jul 16 '18 at 16:02
  • 4
    there's a problem with this answer, I have a button in the view I wanna perform this action in, when the keyboard is up and I click on the button, the keyboard will disappear but I won't get the complete button action, some weird behavior – Arash Afsharpour Apr 28 '19 at 12:40
  • Genius piece of code which I am now adding to my AppDelegate before the class definition or a globals file which can be referenced anywhere. I made 1 change in that I extended UITableViewController. Remember you must also change it in the .dismiss keyboard section also. GREAT!! Thank you! – RandallShanePhD Jan 12 '20 at 18:43
  • 1
    @ArashAfsharpour I have the same problem. Does anyone know how to fix this? – Chris Jun 23 '20 at 09:35
124

An answer to your question on how to dismiss the keyboard in Xcode 6.1 using Swift below:

import UIKit

class ItemViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var textFieldItemName: UITextField!

    @IBOutlet var textFieldQt: UITextField!

    @IBOutlet var textFieldMoreInfo: UITextField!


    override func viewDidLoad() {
        super.viewDidLoad()

        textFieldItemName.delegate = self
        textFieldQt.delegate = self
        textFieldMoreInfo.delegate = self
    }

                       ...

    /**
     * Called when 'return' key pressed. return NO to ignore.
     */
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }


   /**
    * Called when the user click on the view (outside the UITextField).
    */
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.view.endEditing(true)
    }

}

(Source of this information).

crazy_phage
  • 533
  • 8
  • 25
King-Wizard
  • 14,974
  • 4
  • 79
  • 74
  • 7
    Great piece of code, thanks! touchesBegan was exactly what I was looking for :) – Lukasz Czerwinski Jul 01 '15 at 22:42
  • 4
    This didn't quite work for me. If I tap on the view controller's view it works. If I tap on a control item in the view, the keyboard doesn't dismiss. – user3731622 Apr 09 '16 at 18:58
  • This is the best solution I have seen so far. Small note: in newer Swift the override signature changed a bit. You need to add _ before touches: override func touchesBegan(_ touches: Set, withEvent event: UIEvent?) – Regis St-Gelais Dec 12 '18 at 19:57
  • 1
    This one should probably be marked as correct one. The current accepted answer makes every button in the view not responsive when keyboard is showing. – Bartek Spitza Mar 07 '19 at 13:37
  • This doesn't work when tapping inside a tableview or any scrollable. – Mohamed Salah Jun 10 '19 at 15:40
46

Swift 4 working

Create extension as below & call hideKeyboardWhenTappedAround() in your Base view controller.

//
//  UIViewController+Extension.swift
//  Project Name
//
//  Created by ABC on 2/3/18.
//  Copyright © 2018 ABC. All rights reserved.
//

import UIKit

extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tapGesture = UITapGestureRecognizer(target: self, 
                         action: #selector(hideKeyboard))
        view.addGestureRecognizer(tapGesture)
    }

    @objc func hideKeyboard() {
        view.endEditing(true)
    }
}

Most important thing to call in your Base View Controller so that no need to call all time in all view controllers.

Fahim Parkar
  • 28,922
  • 40
  • 153
  • 260
37

You can call

resignFirstResponder()

on any instance of a UIResponder, such as a UITextField. If you call it on the view that is currently causing the keyboard to be displayed then the keyboard will dismiss.

Dash
  • 15,988
  • 6
  • 44
  • 48
  • 5
    In a situation where you don't exactly know the first responder, resignFirstResponder() can lead to a heap of trouble. Esq's answer below (using view.doneEditing()) is a lot more appropriate – shiser Jun 01 '15 at 00:16
  • 1
    Whenever I use resignFirstResponder on my textField the app crashes. I tried everything I could think of, and looked around the web for a fix. Nothing helps me. Would you happen to know why that happens? – AugustoQ Sep 23 '15 at 23:57
  • 1
    As shiser said this is not the best solution. plus it doesn't work in all situations. – Alix Dec 11 '18 at 19:35
21
//Simple exercise to demonstrate, assuming the view controller has a //Textfield, Button and a Label. And that the label should display the //userinputs when button clicked. And if you want the keyboard to disappear //when clicken anywhere on the screen + upon clicking Return key in the //keyboard. Dont forget to add "UITextFieldDelegate" and 
//"self.userInput.delegate = self" as below

import UIKit

class ViewController: UIViewController,UITextFieldDelegate {

    @IBOutlet weak var userInput: UITextField!
    @IBAction func transferBtn(sender: AnyObject) {
                display.text = userInput.text

    }
    @IBOutlet weak var display: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

//This is important for the textFieldShouldReturn function, conforming to textfieldDelegate and setting it to self
        self.userInput.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

//This is for the keyboard to GO AWAYY !! when user clicks anywhere on the view
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.view.endEditing(true)
    }


//This is for the keyboard to GO AWAYY !! when user clicks "Return" key  on the keyboard

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

}
Naishta
  • 9,905
  • 4
  • 60
  • 49
21

for Swift 3 it is very simple

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

if you want to hide keyboard on pressing RETURN key

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

but in second case you will also need to pass delegate from all textFields to the ViewController in the Main.Storyboard

Yerbol
  • 377
  • 2
  • 6
15

swift 5 just two lines is enough. Add into your viewDidLoad should work.

 let tapGesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing))
 view.addGestureRecognizer(tapGesture)

If your tap gesture blocked some other touches, then add this line:

tapGesture.cancelsTouchesInView = false
William Hu
  • 12,918
  • 8
  • 85
  • 98
12

Swift 3: Easiest way to dismiss keyboard:

  //Dismiss keyboard method
    func keyboardDismiss() {
        textField.resignFirstResponder()
    }

    //ADD Gesture Recignizer to Dismiss keyboard then view tapped
    @IBAction func viewTapped(_ sender: AnyObject) {
        keyboardDismiss()
    }

    //Dismiss keyboard using Return Key (Done) Button
    //Do not forgot to add protocol UITextFieldDelegate 
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        keyboardDismiss()

        return true
    }
NikaE
  • 534
  • 1
  • 6
  • 15
  • 1
    I'm fairly sure that the view.endEditing(true) call is simpler in that it doesn't require you to store a variable or assume you only have one text field. – Glenn Howes Nov 22 '16 at 16:19
10

Dash's answer is correct and preferred. A more "scorched earth" approach is to call view.endEditing(true). This causes view and all its subviews to resignFirstResponder. If you don't have a reference to the view you'd like to dismiss, this is a hacky but effective solution.

Note that personally I think you should have a reference to the view you'd like to have resign first responder. .endEditing(force: Bool) is a barbaric approach; please don't use it.

modocache
  • 5,588
  • 3
  • 32
  • 46
10

I found the best solution included the accepted answer from @Esqarrouth, with some adjustments:

extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboardView")
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

    func dismissKeyboardView() {
        view.endEditing(true)
    }
}

The line tap.cancelsTouchesInView = false was critical: it ensures that the UITapGestureRecognizer does not prevent other elements on the view from receiving user interaction.

The method dismissKeyboard() was changed to the slightly less elegant dismissKeyboardView(). This is because in my project's fairly old codebase, there were numerous times where dismissKeyboard() was already used (I imagine this is not uncommon), causing compiler issues.

Then, as above, this behaviour can be enabled in individual View Controllers:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround() 
}
Luke Harries
  • 121
  • 1
  • 7
9

Use IQKeyboardmanager that will help you solve easy.....

/////////////////////////////////////////

![ how to disable the keyboard..][1]

import UIKit

class ViewController: UIViewController,UITextFieldDelegate {

   @IBOutlet weak var username: UITextField!
   @IBOutlet weak var password: UITextField!

   override func viewDidLoad() {
      super.viewDidLoad() 
      username.delegate = self
      password.delegate = self
      // Do any additional setup after loading the view, typically from a nib.
   }

   override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
      // Dispose of any resources that can be recreated.
   }

   func textFieldShouldReturn(textField: UITextField!) -> Bool // called when   'return' key pressed. return NO to ignore.
   {
      textField.resignFirstResponder()
      return true;
   }

   override func touchesBegan(_: Set<UITouch>, with: UIEvent?) {
     username.resignFirstResponder()
     password.resignFirstResponder()
     self.view.endEditing(true)
  }
}
Hardik Bar
  • 1,482
  • 14
  • 23
9

In storyboard:

  1. select the TableView
  2. from the the right-hand-side, select the attribute inspector
  3. in the keyboard section - select the dismiss mode you want
zevij
  • 2,090
  • 1
  • 20
  • 25
9

Swift 3:

Extension with Selector as parameter to be able to do additional stuff in the dismiss function and cancelsTouchesInView to prevent distortion with touches on other elements of the view.

extension UIViewController {
    func hideKeyboardOnTap(_ selector: Selector) {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: selector)
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }
}

Usage:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardOnTap(#selector(self.dismissKeyboard))
}

func dismissKeyboard() {
    view.endEditing(true)
    // do aditional stuff
}
David Seek
  • 15,533
  • 14
  • 94
  • 125
8

To expand on Esqarrouth's answer, I always use the following to dismiss the keyboard, especially if the class from which I am dismissing the keyboard does not have a view property and/or is not a subclass of UIView.

UIApplication.shared.keyWindow?.endEditing(true)

And, for convenience, the following extension to the UIApplcation class:

extension UIApplication {

    /// Dismisses the keyboard from the key window of the
    /// shared application instance.
    ///
    /// - Parameters:
    ///     - force: specify `true` to force first responder to resign.
    open class func endEditing(_ force: Bool = false) {
        shared.endEditing(force)
    }

    /// Dismisses the keyboard from the key window of this 
    /// application instance.
    ///
    /// - Parameters:
    ///     - force: specify `true` to force first responder to resign.
    open func endEditing(_ force: Bool = false) {
        keyWindow?.endEditing(force)
    }

}
NoodleOfDeath
  • 13,338
  • 21
  • 69
  • 100
8

If you use a scroll view, It could be much simpler.

Just select Dismiss interactively in storyboard.

JIE WANG
  • 1,284
  • 13
  • 18
8

Add this extension to your ViewController :

  extension UIViewController {
// Ends editing view when touches to view 
  open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)
    self.view.endEditing(true)
  }
}
Jarvis The Avenger
  • 2,298
  • 1
  • 15
  • 28
7

In Swift 4, add @objc:

In the viewDidLoad:

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
view.addGestureRecognizer(tap)

Function:

@objc func dismissKeyboard() {
  view.endEditing(true)
}
user3856297
  • 253
  • 3
  • 7
7

In swift you can use

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

}
5
  import UIKit

  class ItemViewController: UIViewController, UITextFieldDelegate {

  @IBOutlet weak var nameTextField: UITextField!

    override func viewDidLoad() {
           super.viewDidLoad()
           self.nameTextField.delegate = self
     }

    // Called when 'return' key pressed. return NO to ignore.

    func textFieldShouldReturn(textField: UITextField) -> Bool {

            textField.resignFirstResponder()
             return true
     }

 // Called when the user click on the view (outside the UITextField).

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)    {
      self.view.endEditing(true)
  }
}
5

As a novice programmer it can be confusing when people produce more skilled and unnecessary responses...You do not have to do any of the complicated stuff shown above!...

Here is the simplest option...In the case your keyboard appears in response to the textfield - Inside your touch screen function just add the resignFirstResponder function. As shown below - the keyboard will close because the First Responder is released (exiting the Responder chain)...

override func touchesBegan(_: Set<UITouch>, with: UIEvent?){
    MyTextField.resignFirstResponder()
}
Ingo Karkat
  • 154,018
  • 15
  • 205
  • 275
RedSky
  • 61
  • 1
  • 2
5

I have use IQKeyBoardManagerSwift for keyboard. it is easy to use. just Add pod 'IQKeyboardManagerSwift'

Import IQKeyboardManagerSwift and write code on didFinishLaunchingWithOptions in AppDelegate.

///add this line 
IQKeyboardManager.shared.shouldResignOnTouchOutside = true
IQKeyboardManager.shared.enable = true
Vaisakh KP
  • 437
  • 1
  • 5
  • 21
Amanpreet Kaur
  • 786
  • 7
  • 17
4

This one liner resigns Keyboard from all(any) the UITextField in a UIView

self.view.endEditing(true)
Codetard
  • 2,026
  • 22
  • 33
4

Posting as a new answer since my edit of @King-Wizard's answer was rejected.

Make your class a delegate of the UITextField and override touchesBegan.

Swift 4

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }

    //Called when 'return' key is pressed. Return false to keep the keyboard visible.
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        return true
    }

    // Called when the user clicks on the view (outside of UITextField).
    override func touchesBegan(touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

}
Viktor Sec
  • 2,328
  • 1
  • 19
  • 28
4

Just one line of code in viewDidLoad() method:

view.addGestureRecognizer(UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:))))
double-beep
  • 3,889
  • 12
  • 24
  • 35
Artem
  • 71
  • 3
3

For Swift3

Register an event recogniser in viewDidLoad

let tap = UITapGestureRecognizer(target: self, action: #selector(hideKeyBoard))

then we need to add the gesture into the view in same viewDidLoad.

self.view.addGestureRecognizer(tap)

Then we need to initialise the registered method

func hideKeyBoard(sender: UITapGestureRecognizer? = nil){
    view.endEditing(true)
}
Sandu
  • 409
  • 4
  • 8
2

You can also add a tap gesture recognizer to resign the keyboard. :D

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let recognizer = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
    backgroundView.addGestureRecognizer(recognizer)
}
    func handleTap(recognizer: UITapGestureRecognizer) {
    textField.resignFirstResponder()
    textFieldtwo.resignFirstResponder()
    textFieldthree.resignFirstResponder()

    println("tappped")
}
Codetard
  • 2,026
  • 22
  • 33
2

Another possibility is to simply add a big button with no content that lies underneath all views you might need to touch. Give it an action named:

@IBAction func dismissKeyboardButton(sender: AnyObject) {
    view.endEditing(true)
}

The problem with a gesture recognizer was for me, that it also caught all touches I wanted to receive by the tableViewCells.

Timm Kent
  • 1,046
  • 11
  • 23
2

If you have other views that should receive the touch as well you have to set cancelsTouchesInView = false

Like this:

let elsewhereTap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
    elsewhereTap.cancelsTouchesInView = false
    self.view.addGestureRecognizer(elsewhereTap)
ph1lb4
  • 1,541
  • 11
  • 21
2
override func viewDidLoad() {
        super.viewDidLoad()

self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap)))

}

func tap(sender: UITapGestureRecognizer){
        print("tapped")
        view.endEditing(true)
}

Try this,It's Working

Ramprasath Selvam
  • 2,706
  • 1
  • 19
  • 31
1

When there is more than one text field in the view

To follow @modocache's recommendation to avoid calling view.endEditing(), you could keep track of the text field that became first responder, but that is messy and error-prone.

An alternative is to call resignFirstResponder() on all text fields in the viewcontroller. Here's an example of creating a collection of all text fields (which in my case was needed for validation code anyway):

@IBOutlet weak var firstName: UITextField!
@IBOutlet weak var lastName: UITextField!
@IBOutlet weak var email: UITextField!

var allTextFields: Array<UITextField>!  // Forced unwrapping so it must be initialized in viewDidLoad
override func viewDidLoad()
{
    super.viewDidLoad()
    self.allTextFields = [self.firstName, self.lastName, self.email]
}

With the collection available, it's a simple matter to iterate through all of them:

private func dismissKeyboard()
{
    for textField in allTextFields
    {
        textField.resignFirstResponder()
    }
}

So now you can call dismissKeyboard() in your gesture recognizer (or wherever is appropriate for you). Drawback is that you must maintain the list of UITextFields when you add or remove fields.

Comments welcome. If there is a problem with calling resignFirstResponder() on controls that aren't first responder, or if there's an easy and guaranteed non-buggy way to track the current first responder, I'd love to hear about it!

Community
  • 1
  • 1
stone
  • 7,288
  • 4
  • 48
  • 62
1

I worked out on uisearchbar . See mine.

import UIKit

class BidderPage: UIViewController,UISearchBarDelegate,UITableViewDataSource {

     let recognizer = UITapGestureRecognizer()

// Set recogniser as public in case of tableview and didselectindexpath.


    func searchBarTextDidBeginEditing(searchBar: UISearchBar)

    {

        recognizer.addTarget(self, action: "handleTap:")
        view.addGestureRecognizer(recognizer)

    }

    func handleTap(recognizer: UITapGestureRecognizer) {
        biddersearchbar .resignFirstResponder()
    }
    func searchBarTextDidEndEditing(searchBar: UISearchBar)
    {
        view .removeGestureRecognizer(recognizer)

    }
BenOfTheNorth
  • 2,842
  • 1
  • 17
  • 45
A.G
  • 13,048
  • 84
  • 61
1

I prefer this one-liner:

view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "dismissKeyboardFromView:"))

Just put that in the override viewDidLoad function in whichever subclassed UIViewController you want it to occur, and then put the following code in a new empty file in your project called "UIViewController+dismissKeyboard.swift":

import UIKit

extension UIViewController {
    // This function is called when the tap is recognized
    func dismissKeyboardFromView(sender: UITapGestureRecognizer?) {
        let view = sender?.view
        view?.endEditing(true)
    }
}
gammachill
  • 1,326
  • 1
  • 11
  • 14
1

I got you fam

override func viewDidLoad() {
    super.viewDidLoad() /*This ensures that our view loaded*/
    self.textField.delegate = self /*we select our text field that we want*/   
    self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("dismissKeyboard")))
}

func dismissKeyboard(){ /*this is a void function*/
    textField.resignFirstResponder() /*This will dismiss our keyboard on tap*/
}
ChannelJuanNews
  • 397
  • 1
  • 11
1

I found this simple solution: 1. Add UITapGestureRecognizer to your view Controller 2. Add IBAction to your UITapGestureRecognizer 3. Finally you can resign the first responder

class ViewController: UIViewController
{

@IBOutlet var tap: UITapGestureRecognizer!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var textField: UITextField!
override func viewDidLoad()
{
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}


@IBAction func dismissUsingGesture(_ sender: UITapGestureRecognizer)
{
   self.textField.resignFirstResponder()
    label.text = textField.text!
}
}
Atka
  • 189
  • 1
  • 5
1

Here's a succinct way of doing it:

let endEditingTapGesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:)))
endEditingTapGesture.cancelsTouchesInView = false
view.addGestureRecognizer(endEditingTapGesture)
Sam
  • 49
  • 1
  • 3
1

Swift 3

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

Here is how to dismiss the keyboard by tapping anywhere else, in 2 lines using Swift 5.

(I hate to add another answer, but since this is the top result on Google I will to help rookies like me.)

In your ViewController.swift, find the viewDidLoad() function.

Add these 2 lines:

let tap: UIGestureRecognizer = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing))
        
view.addGestureRecognizer(tap)
Joshua Dance
  • 6,602
  • 3
  • 52
  • 60
0

Able to achieve this by adding a global tap gesture recognizer to the window property in the AppDelegate.

This was a very catch all approach and might not be the desired solution for some but it worked for me. Please let me know if there any pitfalls to this solution.

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        // Globally dismiss the keyboard when the "background" is tapped.
        window?.addGestureRecognizer(
            UITapGestureRecognizer(
              target: window, 
              action: #selector(UIWindow.endEditing(_:))
            )
        )

        return true
    }
}
  • NOTE: The tap gesture steals touch events from a UITabBar / UITabViewController unless you call `tapGestureRecognizer.cancelsTouchesInView = false` – Brandon Erbschloe Apr 24 '20 at 16:44
0

A simple way to do this is by selecting the text field and using the method endEditing(true)

e.g

exampleTextField.endEditing(true)
James Harrys
  • 61
  • 3
  • 6