Dismiss keyboard example in Swift

In this video I am going to show you a couple of different ways to dismiss keyboard.

We will dismiss keyboard when:

  • User taps on a button
  • User taps on a Return key or Done button on a keyboard
  • User taps on a view away from the TextField.

Source code:


import UIKit
class ViewController: UIViewController,UITextFieldDelegate {@IBOutlet weak var myTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// 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.
}

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

@IBAction func myButtonTapped(sender: AnyObject) {

myTextField.resignFirstResponder()
}

func textFieldShouldReturn(textField: UITextField) -> Bool
{

myTextField.resignFirstResponder()

return true

}
}