SwiftUI: How to hide keyboard after using DatePicker
FocusState is not necessary and add an extension of view to hide your keyboard
struct EditView: View {
@Binding var name: String = ""
@State private var birthday: Date = Date()
//@FocusState private var isTextFieldFocused
var body: some View {
Form {
TextField("Name", text: $name)
DatePicker("Birthday", selection: $birthday)
}
.onTapGesture {
hideKeyboard()
}
}
}
extension View {
func hideKeyboard() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
SwiftUI Dismiss Keyboard from UITextField
So I found a trick on my own with an epiphany overnight.
First, I would like to share to anyone else a very basic reason why inb4cookies solution wasn't quite adequate. While I had already tried adding a resignFirstResponder call like it to the onTap
of the background stack, it was triggering the onTap for the VStack
when I was clicking the field.
This is likely because I am using a UITextField
as the back end for this component and not a SwiftUI TextField
.
However, it was partially used in the final solution. I still applied it, but there is an extra step.
VStack {
CustomTextView($viewModel.parameter)
.onTap {/*Insert literally any compiling code here*/ }
/// Other views
}
.onTap {
self.hideKeyboard()
}
You'll see that above, there is an extra onTap
. I tested it with a print
statement, but this will override the onTap
for the VStack
and prevent the keyboard from being dismissed right after it is brought up. Tapping anywhere else on the VStack still closes it, except for Buttons. But I can always add hideKeyboard
to those buttons if needed.
SwiftUI: Hide keyboard but show cursor
You can use UIViewRepresentable
class and pass the input view as an empty view.
struct HideKeyboardTextField: UIViewRepresentable {
var placeholder: String
@Binding var text: String
func makeUIView(context: UIViewRepresentableContext<HideKeyboardTextField>) -> UITextField {
let textField = UITextField(frame: .zero)
textField.placeholder = placeholder
textField.inputView = UIView()
textField.delegate = context.coordinator
return textField
}
func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<HideKeyboardTextField>) {
uiView.text = text
}
func makeCoordinator() -> HideKeyboardTextField.Coordinator {
Coordinator(parent: self)
}
class Coordinator: NSObject, UITextFieldDelegate {
var parent: HideKeyboardTextField
init(parent: HideKeyboardTextField) {
self.parent = parent
}
func textFieldDidChangeSelection(_ textField: UITextField) {
DispatchQueue.main.async {
parent.text = textField.text ?? ""
}
}
}
}
Usage:
struct ContentView: View {
@State var text: String = ""
var body: some View {
HideKeyboardTextField(placeholder: "Input", text: $text)
}
}
SwiftUI dismiss keyboard when tapping segmentedControl
Attach a custom Binding
to the Picker
that calls endEditing()
whenever it is set:
Section(header: Text("Search Type")) {
Picker("", selection: Binding(get: {
self.type
}, set: { (res) in
self.type = res
UIApplication.shared.endEditing()
})) {
Text("By Name").tag("name")
Text("By AppId").tag("id")
}.pickerStyle(SegmentedPickerStyle())
}
How to hide the keyboard when using SwiftUI?
A quick workaround for you:
private var customBinding: Binding<Int> {
Binding(get: {
self.tippercentage
}, set: {
self.tippercentage = $0
UIApplication.shared.windows.forEach { $0.endEditing(true )}
})
}
Then pass customBinding
to Picker
as in selection: customBinding
.
There are more complex solutions to this problem and I would only consider this as a quick workaround.
Related Topics
Using Auto Layout in Uitableview For Dynamic Cell Layouts & Variable Row Heights
What Are Unwind Segues For and How to Use Them
How to Sort an Nsmutablearray With Custom Objects in It
Symbolicating Iphone App Crash Reports
How to Add Exception Breakpoint in Xcode
How to Load an Http Url With App Transport Security Enabled in iOS 9
How to Embed a Custom Font in an Iphone Application
How to Associate File Types With an Iphone Application
How to Change Status Bar Text Color in Ios
Test iOS App on Device Without Apple Developer Program or Jailbreak
Programmatically Get Own Phone Number in Ios
Custom Uitableviewcell from Nib in Swift
How to Find Specific Subclass of Nsmanagedobject
Swift: How to Split Up a [String] Resulting in a [[String]] With a Given Subarray Size
Nsoperation VS Grand Central Dispatch
Submit to App Store Issues: Unsupported Architecture X86