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,268 times
1
Ajoy
- 1,834
- 3
- 30
- 55
Nikhil Sridhar
- 1,510
- 5
- 17
- 36
-
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.
- 5,967
- 4
- 40
- 66
0
Set the delegate of
UITextField, Like asUITableviewDataSource,Delegate. WriteyourTextFieldDelegate.delegate = selfinviewDidLoad()Then, write this function:
func textFieldShouldReturn(textField: UITextField) -> Bool { titleTextField.resignFirstResponder() return true }
4444
- 3,533
- 10
- 29
- 43
iDeveloper
- 2,021
- 1
- 18
- 35