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.
Asked
Active
Viewed 1,276 times
1

Ajoy
- 1,838
- 3
- 30
- 57

Nikhil Sridhar
- 1,670
- 5
- 20
- 39
-
Which delegate methods have you used? – Ajil O. Nov 15 '16 at 07:23
-
Possible duplicate of [Close iOS Keyboard by touching anywhere using Swift](http://stackoverflow.com/questions/24126678/close-ios-keyboard-by-touching-anywhere-using-swift) – Ahmad F Nov 15 '16 at 08:57
-
[Solution is here](http://stackoverflow.com/questions/24126678/close-ios-keyboard-by-touching-anywhere-using-swift?rq=1) For Swift and objective – Tarik Jan 16 '17 at 11:44
2 Answers
1
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.

Ajil O.
- 6,562
- 5
- 40
- 72
0
Set the delegate of
UITextField
, Like asUITableviewDataSource,Delegate
. WriteyourTextFieldDelegate.delegate = self
inviewDidLoad()
Then, write this function:
func textFieldShouldReturn(textField: UITextField) -> Bool { titleTextField.resignFirstResponder() return true }

4444
- 3,541
- 10
- 32
- 43

iDeveloper
- 2,339
- 2
- 24
- 38