Nikhil Sridhar
Nikhil Sridhar

Reputation: 1740

Dismissing Keyboard for UITextField

I'm new to Swift, and I was recently learning about UITextField and how it delegates. I was wondering if there was a simple way to dismiss the keyboard when taping outside of it (somewhere else in the view). Currently, I am using UITapGestureRecognizer to do this. It works, but I was wondering if there was a simpler way to do it.

Upvotes: 1

Views: 1290

Answers (2)

iDeveloper
iDeveloper

Reputation: 2444

  1. Set the delegate of UITextField, Like as UITableviewDataSource,Delegate. Write yourTextFieldDelegate.delegate = self in viewDidLoad()

  2. Then, write this function:

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

Upvotes: 0

Ajil O.
Ajil O.

Reputation: 6892

You can use this method to dismiss the keyboard by tapping anywhere on the screen

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

But be sure to set the delegates beforehand.

Upvotes: 1

Related Questions