【问题标题】:SwiftUI: Hide keyboard but show cursorSwiftUI:隐藏键盘但显示光标
【发布时间】:2021-09-16 20:29:09
【问题描述】:

我想使用自定义按钮将文本输入到TextField,但仍显示和移动光标。有没有办法在显示光标的同时隐藏默认键盘?

我希望是这样的:

TextField("", text: $text)
    .keyboardType(.none)

这是它目前的样子。

【问题讨论】:

    标签: swift swiftui textfield


    【解决方案1】:

    您可以使用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)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-24
      • 2014-12-13
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多