1

I have been trying to make the keyboard dismiss when I touch off the keyboard. I found one piece of code that seems to work (kind of), but it only works if I am not touching any other kind of view. By this I mean, I have a scroll view that takes up the majority of the screen. If I tap off the scroll view it will disappear, but if I tap anywhere on the scroll view, nothing happens. This is the code segment I am using. Any help would be much appreciated.

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}
Carbanim
  • 27
  • 2
  • 8

1 Answers1

2

You can try

let singleTap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
singleTap.numberOfTapsRequired = 1
scrollView.addGestureRecognizer(singleTap)

//

@objc func handleTap(_ recognizer: UITapGestureRecognizer) {
    self.view.endEditing(true)
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • 1
    Thank you, that worked. I need to look a bit more into UITapGestureRecognizer. I don't know a whole lot about it as of yet. Very much appreciated! – Carbanim May 29 '18 at 22:55