我在互聯網上花了幾個小時,但我無法為我的問題找到合適的解決方案。問題如下:我已經stackoverflow使用UIViewRepresentable. UITextField我這樣做是為了能夠在 IOs15 之前優雅地使文本輸入成為第一回應者。我在許多地方和許多不同的頁面中使用此文本欄位。
目前,當用戶開始在我們的自定義文本欄位中輸入文本時,我們需要以下拉串列的形式顯示建議。將要顯示的視圖應恰好出現在每個文本欄位的下方,并且不應破壞現有視圖的流動和定位。當然,我們需要修改我們的文本欄位實作,因為我們在這么多不同的地方使用它不同的方法看起來很辛苦。
一般來說,如何實作這種行為?
下面我發布了我們的文本輸入實作
謝謝
class TextFieldPad: UITextField {
let padding = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
override open func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: padding)
}
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: padding)
}
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: padding)
}
}
struct FocusableTextField: UIViewRepresentable {
class Coordinator: NSObject, UITextFieldDelegate {
@Binding var text: String
var didBecomeFirstResponder = false
init(text: Binding<String>) {
_text = text
}
func textFieldDidChangeSelection(_ textField: UITextField) {
text = textField.text ?? “”
}
}
@Binding var placeHolder: String;
@Binding var text: String
var isFirstResponder: Bool = false
var issecure: Bool = false
var borderColor: UIColor = UIColor(rgb: 0xEEA924);
var backgroundColor: UIColor = UIColor.white;
var placeholderColor: UIColor = UIColor.black;
var textColor: UIColor = UIColor.black;
func makeUIView(context: UIViewRepresentableContext<FocusableTextField>) -> UITextField {
let textField = TextFieldPad(frame: .zero)
textField.layer.borderWidth = 2;
textField.layer.borderColor = borderColor.cgColor
textField.layer.cornerRadius = CGFloat(14.0)
textField.layer.backgroundColor = backgroundColor.cgColor
textField.isSecureTextEntry = issecure
textField.textColor = textColor
textField.autocorrectionType = .no
textField.autocapitalizationType = .none
textField.attributedPlaceholder = NSAttributedString(
string: placeHolder,
attributes: [NSAttributedString.Key.foregroundColor : placeholderColor.cgColor]
)
textField.delegate = context.coordinator
return textField
}
func makeCoordinator() -> FocusableTextField.Coordinator {
return Coordinator(text: $text)
}
func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<FocusableTextField>) {
uiView.text = text
if isFirstResponder && !context.coordinator.didBecomeFirstResponder {
uiView.becomeFirstResponder()
context.coordinator.didBecomeFirstResponder = true
}
}
}
uj5u.com熱心網友回復:
我最終inputAccessoryView通過鍵盤在該視圖中使用并顯示可滾動的建議。
歡迎任何其他意見和建議:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/493468.html
標籤:迅速 代码 迅捷 uitextfield uiviewrepresentable
