How to hide keyboard
using SwiftUI
for below cases?
Case 1
I have TextField
and I need to hide the keyboard
when the user clicks the return
button.
Case 2
I have TextField
and I need to hide the keyboard
when the user taps outside.
How I can do this using SwiftUI
?
Note:
I have not asked a question regarding UITextField
. I want to do it by using SwifUI
(TextField
).
SwiftUI in 'SceneDelegate.swift' file just add: .onTapGesture { window.endEditing(true)}
this is enough for each View using keyboard in your app...
@RyanTCB's answer is good; here are a couple of refinements that make it simpler to use and avoid a potential crash:
The 'bug fix' is simply that
keyWindow!.endEditing(true)
properly should bekeyWindow?.endEditing(true)
(yes, you might argue it can't happen.)More interesting is how you can use it. For example, suppose you have a form with multiple editable fields in it. Just wrap it like this:
Now, tapping on any control that itself doesn't present a keyboard will do the appropriate dismiss.
(Tested with beta 7)
Please check https://github.com/michaelhenry/KeyboardAvoider
Just include
KeyboardAvoider {}
on top of your main view and that's all.Because
keyWindow
is deprecated.I experienced this while using a TextField inside a NavigationView. This is my solution for that. It will dismiss the keyboard when you start scrolling.
Expanding on the answer by @Feldur (which was based on @RyanTCB's), here is an even more expressive and powerful solution allowing you to dismiss keyboard on other gestures than
onTapGesture
, you can specify which you want in the function call.Usage
Or using
All.gestures
(just sugar forGestures.allCases