我在网上花了几个小时,但我找不到适合我的问题的解决方案.问题如下:
目前,当用户开始在自定义文本字段中键入文本时,我们需要以下拉列表的形式显示建议.将要显示的视图应显示在每个文本字段的正下方,并且不应中断现有视图的流动和定位.当然,我们需要修改文本字段实现,因为我们在许多不同的地方使用它,不同的方法看起来非常困难.
一般来说,如何实现这种行为?
Bellow我正在发布我们的文本输入实现
谢谢
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
}
}
}