devOP1
devOP1

Reputation: 477

How to endEditing on UIViewRepresentable in SwiftUI?

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! :)

Upvotes: 0

Views: 1289

Answers (3)

It Worked fine for me.

#if canImport(UIKit)
extension View {
    func hideKeyboard() {
        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}
#endif

Upvotes: 0

Warren Burton
Warren Burton

Reputation: 17382

You're almost correct with the extension on View

Use endEditing on all the windows. That can be called from anywhere.

extension View {
  static func endEditing() {
    UIApplication.shared.windows.forEach { $0.endEditing(false) }
  }
}

That approach might not be correct if you had a multi-scene app.

Upvotes: 1

Dimple
Dimple

Reputation: 21

Add an action to any button or in viewWillDisappear method inside UIViewController class

self.view.endEditing(true)

add this line. This will dismiss keyboard and stops editing.

Upvotes: 0

Related Questions