Casey Casey - 5 months ago 28
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() {
super.viewDidLoad()
self.emailLogin.delegate = self
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}


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() {

view.endEditing(true)
}

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


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

Any info is appreciated!

EDIT:
I could be doing this wrong

Answer

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.