如何在 SwiftUI 中结束对 UIViewRepresentable 的编辑?

How to endEditing on UIViewRepresentable in SwiftUI?

我有一个第一响应者 textField 但我希望能够在点击屏幕或用户按下按钮时关闭键盘。

这是我的 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
    }

}

}

下面是我在视图中的调用方式:

CustomSTPPaymentCardTextField(paymentMethodParams: $paymentMethodParams)

我尝试传递一个绑定布尔值来激活 endEditing

我也尝试过使用以下功能:

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

我也试过以下方法:

UIApplication.shared.resignFirstResponder()

我已经尝试了上述所有方法,有和没有 DispatchQueue.main.async,但其中 none 似乎有效。

感谢任何帮助! :)

向任何按钮或在 UIViewController 内的 viewWillDisappear 方法中添加动作 class

self.view.endEditing(true)

添加这一行。这将关闭键盘并停止编辑。

您在 View

上的 extension 几乎是正确的

对所有 windows 使用 endEditing。可以从任何地方调用。

extension View {
  static func endEditing() {
    UIApplication.shared.windows.forEach { [=10=].endEditing(false) }
  }
}

如果您有一个多场景应用程序,这种方法可能不正确。

对我来说效果很好。

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