简体   繁体   中英

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM