As far as I can tell, the only built in way to dismiss the keyboard from a TextField in SwiftUI is to press return. I would like to make it so I can tap somewhere on the screen other than the TextView and dismiss the keyboard. There is a way to do it like this:
var body: some View {
VStack(alignment: .center, spacing: 0) {
Text("some text")
.frame(maxWidth: .infinity)
.contentShape(Rectangle())
.onTapGesture(
// dismiss keyboard here
)
TextField("text", $binding)
Text("more text")
.frame(maxWidth: .infinity)
.contentShape(Rectangle())
.onTapGesture(
// dismiss keyboard here
)
}
}
That is a bit cumbersome. I would like to do it this way:
var body: some View {
VStack(alignment: .center, spacing: 0) {
Text("some text")
TextField("text", $binding)
Text("more text")
}
.frame(maxWidth: .infinity)
.contentShape(Rectangle())
.onTapGesture(
// dismiss keyboard here
)
}
This works for the most part, but the gesture on the outermost view overrides the gesture of the textfield. When you first press on the textfield the keyboard displays, but when you press it again it dismisses which I don't want. I want the subview gestures to take precedence. If there is a button in the VStack, it should register just the button and not the dismiss gesture. I was looking into GestureMask and ExclusiveGesture but I couldn't find a way. Is there a way anyone knows of?