SwiftUI:隐藏键盘但显示光标 [英] SwiftUI: Hide keyboard but show cursor

查看:27
本文介绍了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)
    }
}

这篇关于SwiftUI:隐藏键盘但显示光标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆