Casey Casey - 1 year ago 128
Swift Question

Dismiss UITextField keyboard?

I have multiple textfields

@IBOutlet var emailLogin: UITextField!
@IBOutlet var passLogin: UITextField!
@IBOutlet var emailSignUp: UITextField!
@IBOutlet var passSignUp: UITextField!

as of now these aren't really needed, because of how I am dismissing it by tapping anywhere on the screen, however I also want it to dismiss when I press the return key.

override func viewDidLoad() {
self.emailLogin.delegate = self
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.dismissKeyboard))

First question: When I need to dismiss with only one I would set the delegate like so, but how do I handle this when I have multiple views that need to be dismissed on return key?

Also, there are two separate views, but both use the same class. Is this a problem for what I am trying to do?

From here

func dismissKeyboard() {


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

This dismisses the keyboard but only for the textfield that I set as self.

Any info is appreciated!

I could be doing this wrong

Answer Source

Change your code to the following and it should work:

@IBOutlet var emailLogin: UITextField?
@IBOutlet var passLogin: UITextField?
@IBOutlet var emailSignUp: UITextField?
@IBOutlet var passSignUp: UITextField?

emailLogin?.delegate = self
passLogin?.delegate = self
emailSignUp?.delegate = self
passSignUp?.delegate = self

The IBOutlets from other class were not initialized when your LoginViewController loads, thus end up with unwrapping nil objects, which is not allowed in Swift. (You should be able to see that in your console output in Xcode.) Use optional variables will prevent that from happening.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download