How to dismiss keyboard on swipe like in WhatsApp in SwiftUI

Viewed 1033

I know there are answers for dismissing keyboard, but mostly they are triggered on tapped outside of the keyboard. As I stated in the question, how to achieve dismissing keyboard on swipe (to bottom).

2 Answers

UIScrollView has keyboardDismissMode which when set to interactive, will achieve what you want. SwiftUI doesn’t provide direct support for this, but since under the hood, SwiftUI is using UIScrollView, you can use this which sets keyboardDismissMode to interactive for all scroll views in your app.

UIScrollView.appearance().keyboardDismissMode = .interactive

You must have a ScrollView in your view hierarchy for this to work. Here’s is a simple view demonstrating the behavior:

struct ContentView: View {
    @State private var text = "Hello, world!"

    var body: some View {
        ScrollView {
            TextField("Hello", text: $text)
                .padding()
        }
        .onAppear {
            UIScrollView.appearance().keyboardDismissMode = .interactive
        }
    }
}

The only caveat is that this affects all scroll views in your app. I don’t know of a simple solution if you only want to affect one scroll view in your app.

For example if you have a list of messages then you can :

List {
    ForEach(...) { ...

    }
}.resignKeyboardOnDragGesture()
extension View {
    func resignKeyboardOnDragGesture() -> some View {
        return modifier(ResignKeyboardOnDragGesture())
    }
}

struct ResignKeyboardOnDragGesture: ViewModifier {
    var gesture = DragGesture().onChanged { _ in
        UIApplication.shared.endEditing(true)
    }
    func body(content: Content) -> some View {
        content.gesture(gesture)
    }
}

By the way it came from here : https://stackoverflow.com/a/58564739/7974174

Related