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
).
You can force the first responder to resign by sending an action to the shared application:
Now you can use this method to close the keyboard whenever you desire:
If you want to close the keyboard with a tap out, you can create a full screen white view with a tap action, that will trigger the
endEditing(_:)
:Seems like the
endEditing
solution is the only one like @rraphael pointed out.The cleanest example I've seen so far is this:
and then using it in the
onCommit:
This method allows you to hide the keyboard on spacers!
First add this function (Credit Given To: Casper Zandbergen, from SwiftUI can't tap in Spacer of HStack)
Next add the following 2 functions (Credit Given To: rraphael, from this question)
The function below would be added to your View class, just refer to the top answer here from rraphael for more details.
Finally, you can now simply call...
This will make any spacer area close the keyboard now. No need for a big white background view anymore!
You could hypothetically apply this technique of
extension
to any controls you need to support TapGestures that do not currently do so and call theonTapGesture
function in combination withself.endEditing()
to close the keyboard in any situation you desire.My solution how to hide software keyboard when users tap outside. You need to use
contentShape
withonTapGesture
to detect the entire View container.You can add it to
SceneDelegate.swift
or call
endEditing
inside any View and anywherewithout
contentShape
with
contentShape
add this modifier to the view you want to detect user taps
I prefer using the .onLongPressGesture(minimumDuration: 0, which does not cause the keyboard to blink when another TextView is activated (side effect of .onTapGesture). The hide keyboard code can be a reusable function.