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) {
}
}