2

I want to use custom buttons to input text into a TextField, but still show and move the cursor. Is there a way to hide the default keyboard while still showing the cursor?

I was hoping for something like this:

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

Here is what it currently looks like.

Here is what it currently looks like

1 Answer 1

3

You can use UIViewRepresentable class and pass the input view as an empty view.

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 ?? ""
            }
        }
    }
}

Usage:

struct ContentView: View {
    
    @State var text: String = ""
    var body: some View {
        HideKeyboardTextField(placeholder: "Input", text: $text)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.