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?
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With