< YALU STUDIO >

Dismiss keyboard in iOS (Swift)

Word count: 202 / Reading time: 1 min
2019/09/01 Share
  1. Add UITextFieldDelegate to the view controller.
  2. In order to enable the return key function, you should implement the textFieldShouldReturn function and set the delegate of the text field to self.
  3. In order to close the keyboard when users touch the screen, you can override the touchesBegan function
Fail to dismiss keyboard in scroll views

Inside a scroll view, touchesBegan function does not work. In order to solve this, one simple way is to go to the storyboard, select the scroll view. In the inspector, find keyboard attribute, and set it to Dismiss on drag. Although it is not as smooth as touches, it can temporarily solve the problem.

Sample code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class exampleViewController: UIViewController, UITextFieldDelegate {

// ...

override func viewDidLoad(){
super.viewDidLoad()

example1TextField.delegate = self
example2TextField.delegate = self
example3TextField.delegate = self

}

// ...

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return true
}

// Dismiss the keyboard when user touches the screen
// It doesn't work when it's in a scroll view
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
CATALOG
  1. 1. Fail to dismiss keyboard in scroll views
  • Sample code