Casey
Casey

Reputation: 164

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

Upvotes: 1

Views: 3506

Answers (2)

shripad20
shripad20

Reputation: 858

Use ViewControllerDelegate to handle tap outside of any textField and textView. It will dismiss keyboard when you tap on outside of textField. Put below code in your view controller:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    super.touchesBegan(touches, withEvent:event)
    self.view.endEditing(true)
}

You don't need to add TapGesture now to handle this.

Upvotes: 0

Cai
Cai

Reputation: 3659

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.

Upvotes: 2

Related Questions