How to dismiss keyboard when touching anywhere outside UITextField (in swift)?

IosSwiftUitextfieldUikeyboard

Ios Problem Overview


I'm working on a project that have a UIViewController, on the view controller there is a UIScrollView and a UITextField on the scrollview. like this: I'm trying to dismiss the keyboard and hide it after typing some text in the textfield and tap anywhere outside the textfield. I've tried the following code:

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

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

It works for me when I tap outside the scrollview, but when I tap on the scrollview nothing happens and the keyboard doesn't hide.

Is there any way to dismiss the keyboard when tapping anywhere outside the textfield? thanks

Ios Solutions


Solution 1 - Ios

Edited for Swift 4

Edit: Added @objc. While this isn't the best option for performance, one instance of it here shouldn't cause too many problems until there is a better solution.

Edited to fix when needing to interact with items behind GestureRecognizer.

Edit: Thanks @Rao for pointing this out. Added tap.cancelsTouchesInView = false.

This should help you with having multiple UITextView or UITextField

Create an extension of the view controller. This has worked much smoother for me and with less hassle than trying to use .resignFirstResponder()

extension UIViewController
{
    func setupToHideKeyboardOnTapOnView()
    {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(
            target: self,
            action: #selector(UIViewController.dismissKeyboard))

        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

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

Call self.setupToHideKeyboardOnTapOnView() in the viewDidLoad

Solution 2 - Ios

Try this, it's tested and working:

For Swift 3.0 / 4.0

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

For Older Swift

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

Solution 3 - Ios

swift 3

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))
}

Solution 4 - Ios

In this case, there is UITapGesture as one of the choices. I tried to create sample code just in case. Like this,

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var scrollView: UIScrollView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let tapGesture = UITapGestureRecognizer(target: self, action: "tap:")
        view.addGestureRecognizer(tapGesture)
    }
    
    func tap(gesture: UITapGestureRecognizer) {
        textField.resignFirstResponder()
    }
}

Solution 5 - Ios

Working Solution for Swift 3 that works with ScrollView

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var scrollView: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // The next line is the crucial part
        // The action is where Swift 3 varies from previous versions
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tap(gesture:)))
        self.view.addGestureRecognizer(tapGesture)
    }

    func tap(gesture: UITapGestureRecognizer) {
        textField.resignFirstResponder()
    }
}

Another question that talks about this issue that I referenced and used. The accepted answer no longer works in Swift 3. The current selected answer should be the below answer.

Solution 6 - Ios

Details

  • Xcode 10.2.1 (10E1001), Swift 5

Solution 1

endEditing(_:)

let gesture = UITapGestureRecognizer(target: tableView, action: #selector(UITextView.endEditing(_:)))
tableView.addGestureRecognizer(gesture)

Usage of solution 1. Full sample

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let textField = UITextField(frame: CGRect(x: 50, y: 50, width: 200, height: 30))
        textField.borderStyle = .roundedRect
        textField.placeholder = "Enter text"
        textField.becomeFirstResponder()
        view.addSubview(textField)
        let gesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:)))
        view.addGestureRecognizer(gesture)
    }
}

Solution 2

> class TapGestureRecognizer

import UIKit

class TapGestureRecognizer: UITapGestureRecognizer {
    
    let identifier: String

    init(target: Any?, action: Selector?, identifier: String) {
        self.identifier = identifier
        super.init(target: target, action: action)
    }
    
    static func == (left: TapGestureRecognizer, right: TapGestureRecognizer) -> Bool {
        return left.identifier == right.identifier
    }
}

> extension UIView

import UIKit

extension UIView {
   
    private var hideKeybordOnTapIdentifier: String { return "hideKeybordOnTapIdentifier" }

    private var hideKeybordOnTapGestureRecognizer: TapGestureRecognizer? {
        let hideKeyboardGesture = TapGestureRecognizer(target: self, action: #selector(UIView.hideKeyboard),
                                                       identifier: hideKeybordOnTapIdentifier)
        if let gestureRecognizers = self.gestureRecognizers {
            for gestureRecognizer in gestureRecognizers {
                if let tapGestureRecognizer = gestureRecognizer as? TapGestureRecognizer,
                    tapGestureRecognizer == hideKeyboardGesture {
                    return tapGestureRecognizer
                }
            }
        }
        return nil
    }
    
    @objc private func hideKeyboard() { endEditing(true) }
    
    var hideKeyboardOnTap: Bool {
        set {
            let hideKeyboardGesture = TapGestureRecognizer(target: self, action: #selector(hideKeyboard),
                                                           identifier: hideKeybordOnTapIdentifier)
            if let hideKeybordOnTapGestureRecognizer = hideKeybordOnTapGestureRecognizer {
                removeGestureRecognizer(hideKeybordOnTapGestureRecognizer)
                if gestureRecognizers?.count == 0 { gestureRecognizers = nil }
            }
            if newValue { addGestureRecognizer(hideKeyboardGesture) }
        }
        get { return hideKeybordOnTapGestureRecognizer == nil ? false : true }
    }
}

Usage of solution 2

view.hideKeyboardOnTap = true

Solution 2 full Sample

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let textField = UITextField(frame: CGRect(x: 50, y: 50, width: 200, height: 30))
        textField.borderStyle = .roundedRect
        textField.placeholder = "Enter text"
        textField.becomeFirstResponder()
        view.addSubview(textField)
        view.hideKeyboardOnTap = true
    }
}

Solution 7 - Ios

Check this out.

override func viewDidLoad() {
    var tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleTap))
    self.view.userInteractionEnabled = true
    self.view.addGestureRecognizer(tapGesture)
}

Then your tap handler is.

  func handleTap(sender: UITapGestureRecognizer) {
    self.view.endEditing(true)
}

Solution 8 - Ios

For Swift 3

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

Solution 9 - Ios

This works when touched outside input area for any number of input items.

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

Solution 10 - Ios

I had the same problem and i finally solved it !

Set a TapGestureRecognizer in your Storyboard and then an Outlet in your ViewController

@IBOutlet var tapGesture: UITapGestureRecognizer!

Then set an IBAction in your ViewController

@IBAction func DismissKeyboard(sender: UITapGestureRecognizer)
{
 self.view.endEditing(true)
} 

add these lines to your viewDidLoad method

override func viewDidLoad()
{
    super.viewDidLoad()
    self.view.addGestureRecognizer(tapGesture)
}

and its should work

Hope that will help !

Solution 11 - Ios

Every touch different of text field dismiss the keyboard or use resignfirstresponder

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
 UITouch *touch = [touches anyObject];
 if(![touch.view isMemberOfClass:[UITextField class]]) {
     [touch.view endEditing:YES];
 }
}

Solution 12 - Ios

func findAndResignFirstResponder(_ stView: UIView) -> Bool {
    
    if stView.isFirstResponder {
        stView.resignFirstResponder()
        return true
    }
    for subView: UIView in stView.subviews {
        if findAndResignFirstResponder(subView) {
            return true
        }
    }
    return false
}

Solution 13 - Ios

I created this method in Obj-C that hides a keyboard no matter where the user is currently typing:

//call this method
+ (void)hideKeyboard {
    //grab the main window of the application
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    //call our recursive method below
    [self resignResponderForView:window];
}

//our recursive method
+ (void)resignResponderForView:(UIView *)view {
    //resign responder from this view
    //If it has the keyboard, then it will hide the keyboard
    [view resignFirstResponder];
    //if it has no subviews, then return back up the stack
    if (view.subviews.count == 0)
        return;
    //go through all of its subviews
    for (UIView *subview in view.subviews) {
        //recursively call the method on those subviews
        [self resignResponderForView:subview];
    }
}

I hope that that is translate-able into Swift and makes sense. It can be called anywhere in the application and will hide the keyboard no matter what VC you're on or anything.

Solution 14 - Ios

Go to Keyboard Type and Select Default or whatever you need the TextField for. Then override a method call it whatever you want i usually call it touchingBegins. Below is what you forgot to add

super.touchingBegins(touches, withEvent: event)
 }

Solution 15 - Ios

Introduce a tap gesture recogniser and set and action for it.

Use the code:

nameofyourtextfield.resignfirstresponder()

Solution 16 - Ios

//In swift 4..It worked for me.

func setupKeyboardDismissRecognizer(){
    let tapRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(searchingActivity.dismissKeyboard))
    
    self.view.addGestureRecognizer(tapRecognizer)
}
    
    @objc func dismissKeyboard()
    {
        view.endEditing(true)
        searchTableView.isHidden = true
    }

//Call this function setupKeyboardDismissRecognizer() in viewDidLoad

Solution 17 - Ios

In Swift4

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

Solution 18 - Ios

In Swift 4 or 5 You can use like..

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    //Key borad dismiss
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
    tap.cancelsTouchesInView = false
    view.addGestureRecognizer(tap)
  }

 //Key board hide on outside the textfield
 @objc func dismissKeyboard() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    view.endEditing(true)
  }
}

Solution 19 - Ios

I used the following code in Swift 4, you can try this,

override func viewDidLoad() {
    super.viewDidLoad()

    // dismiss keyboard when tap outside a text field 
    let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(YourViewControllerName.dismissKeyboard))
    view.addGestureRecognizer(tapGestureRecognizer)
}

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWhite HatView Question on Stackoverflow
Solution 1 - IosMatthew BradshawView Answer on Stackoverflow
Solution 2 - IosiAnuragView Answer on Stackoverflow
Solution 3 - IosGiangView Answer on Stackoverflow
Solution 4 - IospixyzehnView Answer on Stackoverflow
Solution 5 - IosDevbot10View Answer on Stackoverflow
Solution 6 - IosVasily BodnarchukView Answer on Stackoverflow
Solution 7 - IoshandiansomView Answer on Stackoverflow
Solution 8 - IosDavina ArnoldView Answer on Stackoverflow
Solution 9 - IosVenkat RamView Answer on Stackoverflow
Solution 10 - IosLynkz7View Answer on Stackoverflow
Solution 11 - IosMiguel MonteiroView Answer on Stackoverflow
Solution 12 - IosSubhajitView Answer on Stackoverflow
Solution 13 - IosAlexKorenView Answer on Stackoverflow
Solution 14 - IosKatzView Answer on Stackoverflow
Solution 15 - IoskuniView Answer on Stackoverflow
Solution 16 - IosRaghib ArshiView Answer on Stackoverflow
Solution 17 - IosRaghib ArshiView Answer on Stackoverflow
Solution 18 - IosEnamul HaqueView Answer on Stackoverflow
Solution 19 - IosVarun P VView Answer on Stackoverflow