Hide keyboard on tap outside in SwiftUI

In this tutorial, we will see how to hide the keyboard on tap outside in SwiftUI.

We can achieve this task by creating an invisible button that will cover the entire screen. This invisible button will act as an overlay, and when we tap anywhere on the screen, the button will trigger an action to dismiss the keyboard.

Example

import SwiftUI

struct ContentView: View {
    @State private var text: String = ""

    var body: some View {
        // ZStack to place views on top of each other
        ZStack {
            Button(action: {
                self.hideKeyboard() //Calls the hideKeyboard function when tapped
            }) {
                Color.clear //Transparent color to cover the entire screen
            }
            .edgesIgnoringSafeArea(.all) //Ignores safe area to cover all edges

            VStack {
                // TextField for user input, bound to the 'text' state variable
                TextField("Enter text", text: $text)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .padding()
            }
        }
    }

    // Function to hide the keyboard
    private func hideKeyboard() {
        UIApplication.shared.sendAction (
            #selector(UIResponder.resignFirstResponder),
            to: nil,
            from: nil,
            for: nil
        )
    }
}

Output:

Hide keyboard on tap outside in SwiftUI

Leave a Reply

Your email address will not be published. Required fields are marked *