I have a first responder textField
but I want to be able to close the keyboard when the screen is tapped or when the user presses a button.
Here is my UIViewRepresentable
:
public struct CustomSTPPaymentCardTextField: UIViewRepresentable {
@Binding var paymentMethodParams: STPPaymentMethodParams?
let background: Color = ColorManager.backgroundColor
public init(paymentMethodParams: Binding<STPPaymentMethodParams?>) {
_paymentMethodParams = paymentMethodParams
}
public func makeCoordinator() -> Coordinator {
return Coordinator(parent: self)
}
public func makeUIView(context: Context) -> STPPaymentCardTextField {
let paymentCardField = STPPaymentCardTextField()
paymentCardField.borderColor = nil
paymentCardField.borderWidth = 0
paymentCardField.becomeFirstResponder()
return paymentCardField
}
public func updateUIView(_ paymentCardField: STPPaymentCardTextField, context: Context) {
}
public class Coordinator: NSObject, STPPaymentCardTextFieldDelegate {
var parent: CustomSTPPaymentCardTextField
init(parent: CustomSTPPaymentCardTextField) {
self.parent = parent
}
}
}
Here is how I called it in the view:
CustomSTPPaymentCardTextField(paymentMethodParams: $paymentMethodParams)
I’ve tried to pass a binding boolean to activate endEditing
I’ve also tried to use the following function:
#if canImport(UIKit)
extension View {
func hideKeyboard() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
#endif
I’ve also tried the following:
UIApplication.shared.resignFirstResponder()
I’ve tried all of the above methods with and without DispatchQueue.main.async
but none of them seem to work.
Any help is appreciated! 🙂
3
Answers
Add an action to any button or in viewWillDisappear method inside UIViewController class
add this line. This will dismiss keyboard and stops editing.
You’re almost correct with the
extension
onView
Use
endEditing
on all the windows. That can be called from anywhere.That approach might not be correct if you had a multi-scene app.
It Worked fine for me.