How to Hide Keyboard in SwiftUI: Tips and Tricks

SwiftUI doesn't come with a built-in method to dismiss the keyboard in your application when the user taps outside of the keyboard area. Fortunately, it's pretty easy to implement and only requires a few lines of code.

Use a View extension to dismiss the keyboard when the user taps outside of the keyboard area.

Create an extension 

Start by creating a View extension:

extension View {
    func hideKeyboard() {
        let resign = #selector(UIResponder.resignFirstResponder)
        UIApplication.shared.sendAction(resign, to: nil, from: nil, for: nil)
    }
}

..

Call the function in your View 

Then, simply call the method in your View onTapGesture:

var body: some View {
	VStack {
		TextField("Email address", text: $email)
		SecureField("Password", text: $email)
		Button(action: {
		}) {
				Text("Sign in")
						.fontWeight(.semibold)
		}
	}
	.onTapGesture {
			hideKeyboard()
	}
}

..

In the code above, when the user taps anywhere on the VStack, the keyboard will be dismissed. And voilĂ ! It's as simple as that.

Comments