我们如何显示建议UITextField是xCode Swift?



我在网上花了几个小时,但我无法找到适合我的问题的解决方案。问题如下:我已经实现了文本文件,(在stackoverflowpost的帮助下)使用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
}
}
}

我最终使用inputAccessoryView并在键盘视图中显示可滚动的建议。

欢迎任何其他意见和建议:)

最新更新