如何解决SwiftUI:隐藏键盘但显示光标
我想使用自定义按钮将文本输入到 TextField
中,但仍然显示和移动光标。有没有办法在仍然显示光标的同时隐藏默认键盘?
我希望有这样的事情:
TextField("",text: $text)
.keyboardType(.none)
这是它目前的样子。
解决方法
您可以使用 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)
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。