SwiftUI Dismiss Keyboard on outside tap

Cyubahiro Tresor
1 min readAug 28, 2020
Image by Brad McNally

When building forms in your app, it will make the user experience even better when a user can just dismiss the keyboard by tapping anywhere outside a TextField. So how can you achieve this behaviour in SwiftUI?

Enter UIResponder.resignFirstResponder!

Per Apple’s documentation UIResponder is an abstract interface for responding to and handling events. So, to dismiss the keyboard, we will utilise this interface to handle the dismissal for us!

To make this behaviour accessible to any view, we will extend the View class and add this capability to all the views.

Once we have this extension created, now every class extending the View class will have this function available to it by calling self.hideKeyboard().

--

--