Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dismiss keyboard when touching anywhere outside UITextField (in swift)?

I'm working on a project that have a UIViewController, on the view controller there is a UIScrollView and a UITextField on the scrollview. like this: I'm trying to dismiss the keyboard and hide it after typing some text in the textfield and tap anywhere outside the textfield. I've tried the following code:

override func viewDidLoad() {     super.viewDidLoad()     self.textField.delegate = self; }  override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {     self.view.endEditing(true) } 

It works for me when I tap outside the scrollview, but when I tap on the scrollview nothing happens and the keyboard doesn't hide.

Is there any way to dismiss the keyboard when tapping anywhere outside the textfield? thanks

like image 704
White Hat Avatar asked Aug 29 '15 00:08

White Hat


People also ask

How do you dismiss a keyboard when tapping outside Swift?

Via Tap Gesture This is the quickest way to implement keyboard dismissal. Just set a Tap gesture on the main View and hook that gesture with a function which calls view. endEditing . Causes the view (or one of its embedded text fields) to resign the first responder status.

How do you dismiss a keyboard?

Android devices have a solution; press the physical back button (provided on some mobile phones) or the soft key back button, and it closes the keyboard.

How do I dismiss a swift TextField keyboard?

If you're supporting only iOS 15 and later, you can activate and dismiss the keyboard for a text field by focusing and unfocusing it. In its simplest form, this is done using the @FocusState property wrapper and the focusable() modifier – the first stores a Boolean that tracks whether the second is currently focused.


1 Answers

Edited for Swift 4

Edit: Added @objc. While this isn't the best option for performance, one instance of it here shouldn't cause too many problems until there is a better solution.

Edited to fix when needing to interact with items behind GestureRecognizer.

Edit: Thanks @Rao for pointing this out. Added tap.cancelsTouchesInView = false.

This should help you with having multiple UITextView or UITextField

Create an extension of the view controller. This has worked much smoother for me and with less hassle than trying to use .resignFirstResponder()

extension UIViewController {     func setupToHideKeyboardOnTapOnView()     {         let tap: UITapGestureRecognizer = UITapGestureRecognizer(             target: self,             action: #selector(UIViewController.dismissKeyboard))          tap.cancelsTouchesInView = false         view.addGestureRecognizer(tap)     }      @objc func dismissKeyboard()     {         view.endEditing(true)     } } 

Call self.setupToHideKeyboardOnTapOnView() in the viewDidLoad

like image 151
Matthew Bradshaw Avatar answered Sep 30 '22 09:09

Matthew Bradshaw