我想使用自定义按钮将文本输入到 TextField
中,但仍然显示和移动光标。有没有办法在仍然显示光标的同时隐藏默认键盘?
我希望有这样的事情:
TextField("", text: $text)
.keyboardType(.none)
这是它目前的样子。
答案 0 :(得分:0)
您可以使用 UIViewRepresentable
类并将输入视图作为空视图传递。
struct HideKeyboardTextField: UIViewRepresentable {
var placeholder: String
@Binding var text: String
func makeUIView(context: UIViewRepresentableContext<HideKeyboardTextField>) -> UITextField {
let textField = UITextField(frame: .zero)
textField.placeholder = placeholder
textField.inputView = UIView()
textField.delegate = context.coordinator
return textField
}
func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<HideKeyboardTextField>) {
uiView.text = text
}
func makeCoordinator() -> HideKeyboardTextField.Coordinator {
Coordinator(parent: self)
}
class Coordinator: NSObject, UITextFieldDelegate {
var parent: HideKeyboardTextField
init(parent: HideKeyboardTextField) {
self.parent = parent
}
func textFieldDidChangeSelection(_ textField: UITextField) {
DispatchQueue.main.async {
parent.text = textField.text ?? ""
}
}
}
}
用法:
struct ContentView: View {
@State var text: String = ""
var body: some View {
HideKeyboardTextField(placeholder: "Input", text: $text)
}
}