I am trying to workout how to dismiss a keyboard in SwiftUI when the user taps outside a TextField. I followed some other posts that suggested using onTapGesture on a VStack and extending the View protocol to have a method to dismiss the keyboard that is called from the onTapGesture.
This is my content view:
struct ContentView: View {
@State var text = ""
var body: some View {
VStack{
Spacer()
TextField("Text", text: $text)
Text("\(text)")
Spacer()
}
.onTapGesture {
dismissKeyboard()
}
}
}
and I have extended the View protocol with:
extension View {
func dismissKeyboard() {
print("dismissing keyboard")
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
When I run the app, the keyboard is only dismissed when I tap in the area of the Text(). I would understand why this occurs if the Spacers are not there as the VStack only fills the area required by the views that it contains but I expected that the spacers would allow the onTapGesture to work for the whole screen as the VStack is pushed to the top and bottom of the screen but it still only works when tapping the Text().
Is there a reason why the onTapGesture doesn't work when I tap where the Spacers are and only works where the Text is?
.background(Color.red)
to the VStack it will work. It seems like either the TextField or the double Spacers might be causing the frame to be weird. I don't know why though. – aheze