![](/img/trans.png)
[英]How to reload collectionview in UIViewRepresentable SwiftUI
[英]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)
我試圖通過綁定 boolean 來激活endEditing
我還嘗試使用以下 function:
#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
的所有上述方法,但它們似乎都不起作用。
任何幫助表示贊賞::)
您對View
的extension
幾乎是正確的
在所有 windows 上使用endEditing
。 可以從任何地方調用。
extension View {
static func endEditing() {
UIApplication.shared.windows.forEach { $0.endEditing(false) }
}
}
如果您有一個多場景應用程序,這種方法可能不正確。
在 UIViewController class 內的任何按鈕或 viewWillDisappear 方法中添加操作
self.view.endEditing(true)
添加這一行。 這將關閉鍵盤並停止編輯。
它對我來說很好。
#if canImport(UIKit)
extension View {
func hideKeyboard() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
#endif
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.