6

I looked at and tried multiple solutions for Swift 3, Xcode 8 but couldn't get any to work. I've tried:

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

and also setting a text field input as first responder:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {            
    pressureInput.resignFirstResponder()
}

I don't know if something from Xcode 8 to Xcode 9 that cause these methods to not work, or if I messed elsewhere. I have 9 text fields and they've all set delegate to self. Their tags are incremented to move on to the next text field on pressing return. Don't think that would affect it. Sorry, new at this! The code runs fine with either of those attempted functions, but they keyboard stays. I would just like to dismiss keyboard when touched outside of any text field.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Yi Li
  • 133
  • 1
  • 1
  • 6
  • 1
    Show where that code is. Be specific and complete. Provide enough info to allow someone else to run your code and see what the problem is. These are not delegate methods so it is unclear what your architecture is intended to be. – matt Nov 14 '17 at 19:10

5 Answers5

23

first of all write this extension in any swift file

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

    }

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

Than in viewDidLoad of that View only call in any view controller there are textFields.

self.hideKeyboardWhenTappedAround()
anshul king
  • 558
  • 4
  • 17
  • This worked, thanks! Although it did make me put @objc in front of func dismissKeyboard due to #selector. Other than that, it's great. Do you know the reason touchesBegan cannot achieve this? Is it due to the text fields being in a scroll view? If I just write a single text field in the starting view, the touchesBegan method works just fine. – Yi Li Nov 16 '17 at 01:47
  • do not use in selector. – anshul king Nov 16 '17 at 04:53
  • Call this method n viewDidLoad. If this works than hit + my answer. – anshul king Nov 16 '17 at 04:54
2

Swift 4, 5. I always use hide keyboard when tapped around and return button.

override func viewDidLoad() {
    super.viewDidLoad()
    hideKeyboardWhenTappedAround()
    emailTextField.delegate = self // your UITextfield
    passwordTextField.delegate = self // your UITextfield
}

// Hide Keyboard

extension EmailAutorization: UITextFieldDelegate {

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

// Around tapped
func hideKeyboardWhenTappedAround() {
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(EmailAutorization.dismissKeyboard))
    tap.cancelsTouchesInView = false
    view.addGestureRecognizer(tap)
}

@objc func dismissKeyboard() {
    view.endEditing(true)
 }
}
Fabio
  • 5,432
  • 4
  • 22
  • 24
Evgeniy
  • 96
  • 1
  • 4
1

Here is Solution of Dismiss Keyboard and Move View Up on Keyboard Open : Swift 5

   override func viewDidLoad() {
    super.viewDidLoad()
    let tap = UITapGestureRecognizer(target: self, action: #selector(taped))
    view.addGestureRecognizer(tap)
    NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}

 //This Method Will Hide The Keyboard
@objc func taped(){
  self.view.endEditing(true)   
}

@objc func KeyboardWillShow(sender: NSNotification){

    let keyboardSize : CGSize = ((sender.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size)!
    if self.view.frame.origin.y == 0{
        self.view.frame.origin.y -= keyboardSize.height
    }

}

@objc func KeyboardWillHide(sender : NSNotification){

    let keyboardSize : CGSize = ((sender.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size)!
    if self.view.frame.origin.y != 0{
        self.view.frame.origin.y += keyboardSize.height
    }

}
   override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(true)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
Imran Rasheed
  • 825
  • 10
  • 25
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – codedge May 02 '20 at 12:26
0

Are you sure that touchesBegan is being called? If you're sure, try adding self.resignFirstResponder() to your touchesBegan function. This tells your view controller that it's no longer the first responder and should dismiss the keyboard.

If not, what you'll want to do is create a UITapGestureRecognizer, add it to your view, and wire it to a function that calls self.resignFirstResponder().

0

Did you tried to debug the program to see if the code stops in the function at all(with break point)? Usually this code should work...Check if those textFields are in the super view or in a child view and if they are maybe you should call self.childView.endEditing(true).

If you really work with multiple textFields maybe you should try IQKeyboardManager library. I use it in all my projects. You can find it here: https://github.com/hackiftekhar/IQKeyboardManager. Simple to use and with good support. Just install it trough cocoa pods, put IQKeyboardManager.sharedManager().enable = true in the AppDelegate and you're ready to go. :)

R.Radev
  • 81
  • 7
  • You're right. The code doesn't stop at the break point that is inside the function. The fields are in a child view that is in a scroll view, but I'm not able to call self.childView. – Yi Li Nov 15 '17 at 05:37
  • Hm... maybe you can try some of these https://stackoverflow.com/questions/5143873/dismissing-the-keyboard-in-a-uiscrollview – R.Radev Nov 15 '17 at 14:54