How to dismiss keyboard in SwiftUI

I am trying to dismiss keyboard with SwiftUI, by clicking a button, and tap outside the keyboard area

I have read some tutorial and then below is my code.

The result is, when the keyboard is not showing, the button is press-able and can print, but once the keyboard appear, the button is un-press-able, and can not dismiss the keyboard.

For the .onTapGesture one, it works when keyboard appear + tap on the empty area of the UITextView, but not as I expected to work when tapping the Section{}, while I put the .onTapGesture at the end of Section{}

So, what is the proper way to dismiss keyboard with SwiftUI?
(by clicking a button, and tap outside the keyboard area)

thanks

import SwiftUI

struct EditParagraphView: View {
    var body: some View {
        Section{
            VStack{
                Spacer()
                Button(action: {
                    hideKeyboard()
                    print("dismiss")
                }, label: {
                    /*@START_MENU_TOKEN@*/Text("Button")/*@END_MENU_TOKEN@*/
                })
                CodeTextView()
                    .frame(width: 300, height: 450, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
                Spacer()
            }
        }
        .onTapGesture {
            self.hideKeyboard()
        }
    }
}

extension EditParagraphView{
    func hideKeyboard(){
        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}
import SwiftUI

struct CodeTextView: UIViewRepresentable {
    
    @State var tempText = "tempText"
    
    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
        textView.backgroundColor = UIColor.gray
        textView.textColor = UIColor.white
        textView.font = UIFont(name: "Helvetica_Light", size: 20)
        textView.textAlignment = .left
        textView.keyboardType = .default
        textView.returnKeyType = .default
        textView.isEditable = true
        textView.isSelectable = true
        
        textView.text = tempText
        
        return textView
    }
    func updateUIView(_ uiView: UITextView, context: Context) {
        
    }
}

Why are you accessing UIKit for a UITextView?? Rather than using a TextField??

SwiftUI has made this much easier by automatically making this functionality of dismissing a keyboard work, when using SwiftUI views

I want to create a field for input and edit a whole paragraph.
The TextField seems can only support a single line of input, and can’t set the height of the field

If you are targeting iOS 14+ you can use SwiftUI’s TextEditor.

1 Like

Seems very nice feature, I will try that out, thanks very much