How can I dismiss the keyboard after the user clicks outside the TextField
using SwiftUI?
I created a TextField
using SwiftUI, but I couldn't find any solution for dismissing the keyboard if the user clicks outside the TextField
. I took a look at all attributes of TextField
and also the SwiftUI TextField documentation and I couldn't find anything related with dismissing keyboard.
This is my view's code:
struct InputView: View {
@State var inputValue : String = ""
var body: some View {
VStack(spacing: 10) {
TextField("$", text: $inputValue)
.keyboardType(.decimalPad)
}
}
}
This can be done with a view modifier.
public extension View {
func dismissKeyboardOnTap() -> some View {
modifier(DismissKeyboardOnTap())
}
}
public struct DismissKeyboardOnTap: ViewModifier {
public func body(content: Content) -> some View {
#if os(macOS)
return content
#else
return content.gesture(tapGesture)
#endif
}
private var tapGesture: some Gesture {
TapGesture().onEnded(endEditing)
}
private func endEditing() {
UIApplication.shared.connectedScenes
.filter {$0.activationState == .foregroundActive}
.map {$0 as? UIWindowScene}
.compactMap({$0})
.first?.windows
.filter {$0.isKeyWindow}
.first?.endEditing(true)
}
}
backgroundView()
.dismissKeyboardOnTap()
Check out the demo here: https://github.com/youjinp/SwiftUIKit
here is the solution using DragGesture it's working.
struct ContentView: View {
@State var text: String = ""
var body: some View {
VStack {
TextField("My Text", text: $text)
.keyboardType(.decimalPad)
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
.edgesIgnoringSafeArea(.all)
.gesture(
TapGesture()
.onEnded { _ in
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With