How would you dismiss keyboard inside text editor?

195 Views Asked by At

I haven't found any documentation on it. I know you can dismiss keyboard using .keyboardDismissMode on TabliewView and other UIViews but how would you do that with TextEditor() in SwiftUI? I have a swipe gesture feature right now but that doesn't work when the text editor gets long and has to scroll due to which it doesnt recognize gestures anymore.

code:

VStack{
        TextEditor(text: $newNote)
        }
            .gesture(DragGesture(minimumDistance: 20, coordinateSpace: .global)
            .onEnded({ value in
                if value.translation.width < 0 {
                    // left
                }
                
                if value.translation.width > 0 {
                    self.presentationMode.wrappedValue.dismiss()
                    hideKeyboard()
                    self.navigationBarBackButtonHidden = false
                    
                }
                if value.translation.height < 0 {
                    
                }
                
                if value.translation.height > 0 {
                    hideKeyboard()
                    self.navigationBarBackButtonHidden = false
                    
                }
            }
                     
                    ))


 extension View {

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

There are 1 best solutions below

0
Asperi On

Xcode 14 / iOS 16

Now SwiftUI has built-in modifier to manage this:

    TextEditor(text: $text)
       .scrollDismissesKeyboard(.immediately)   // << here !!