Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextField SwiftUI Dismiss Keyboard

How can I dismiss the keyboard after the user clicks outside the TextField using SwiftUI?

I created a TextField using SwiftUI, but I couldn't find any solution for dismissing the keyboard if the user clicks outside the TextField. I took a look at all attributes of TextField and also the SwiftUI TextField documentation and I couldn't find anything related with dismissing keyboard.

This is my view's code:

struct InputView: View {
    @State var inputValue : String = ""
    var body: some View {

        VStack(spacing: 10) {
            TextField("$", text: $inputValue)
                .keyboardType(.decimalPad)
        }
    }
}
like image 615
Jujuba Avatar asked Oct 19 '25 01:10

Jujuba


2 Answers

This can be done with a view modifier.

Code

public extension View {
    func dismissKeyboardOnTap() -> some View {
        modifier(DismissKeyboardOnTap())
    }
}

public struct DismissKeyboardOnTap: ViewModifier {
    public func body(content: Content) -> some View {
        #if os(macOS)
        return content
        #else
        return content.gesture(tapGesture)
        #endif
    }

    private var tapGesture: some Gesture {
        TapGesture().onEnded(endEditing)
    }

    private func endEditing() {
        UIApplication.shared.connectedScenes
            .filter {$0.activationState == .foregroundActive}
            .map {$0 as? UIWindowScene}
            .compactMap({$0})
            .first?.windows
            .filter {$0.isKeyWindow}
            .first?.endEditing(true)
    }
}

Usage

backgroundView()
   .dismissKeyboardOnTap()

Check out the demo here: https://github.com/youjinp/SwiftUIKit

like image 84
youjin Avatar answered Oct 21 '25 14:10

youjin


here is the solution using DragGesture it's working.

struct ContentView: View {
    @State var text: String = ""
    var body: some View {
        VStack {
            TextField("My Text", text: $text)
                .keyboardType(.decimalPad)
        }
        .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
        .edgesIgnoringSafeArea(.all)
        .gesture(
            TapGesture()
                .onEnded { _ in
                    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
            }
        )
    }
}
like image 39
Ruchi Makadia Avatar answered Oct 21 '25 14:10

Ruchi Makadia