Sentry Answers>Swift>

Dismissing the keyboard in SwiftUI

Dismissing the keyboard in SwiftUI

Lazar Nikolov

The Problem

There are cases where we want to manually dismiss the iOS keyboard, either by tapping on a certain button, or after submitting a form. Tapping away from the focused element will not dismiss the keyboard by default.

The Solution

To achieve that, there is a nifty utility function that you can create in your project. Create a KeyboardUtils.swift file within your project and paste the following code:

Click to Copy
import UIKit func hideKeyboard() { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) }

The function sends a resignFirstResponder action to the shared UIApplication, which makes any selected element let go of the focus and dismiss the keyboard.

We can use this function in a form handler:

Click to Copy
func handleCreate() { // ... // send create API call // ... // clear the form fields self.amount = "" self.date = Date() self.note = "" // dismiss the keyboard hideKeyboard() }

Or we can even create a toolbar with a keyboard dismiss button thatll be present on top of our keyboard:

Click to Copy
// create a toolbar at the root of our form .toolbar { // set the placement of the toolbard to the keyboard ToolbarItemGroup(placement: .keyboard) { Spacer() // create a keyboard dismiss button Button { // dismiss the keyboard on press hideKeyboard() } label: { Label("Dismiss", systemImage: "keyboard.chevron.compact.down") } } }
  • ResourcesSentry vs. Crashlytics: The Mobile Developer's Decision-Making Guide (opens in a new tab)
  • Syntax.fmListen to the Syntax Podcast (opens in a new tab)
  • SentrySwift Error & Performance Monitoring (opens in a new tab)
  • Syntax.fm logo
    Listen to the Syntax Podcast (opens in a new tab)

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 150,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.