3

For swiftui are there anything for disable/prevent keyboard from showing up for TextField?

because I am designing a calculator and getting the input from the design instead of keyboard

1
  • 1
    Just use Text, if you don't want user input Commented Jan 4, 2022 at 21:12

2 Answers 2

2

You can use UITextField with UIViewRepresentable, which lets you stop the keyboard from showing up.

import SwiftUI

struct KeyboardView: View {
    @State var text: String = ""
    @State var placHolder: String = "Enter username"
    var body: some View {
        VStack {
            Spacer()
            MyTextField(currentText: $text, placeHolder: $placHolder)
                .padding(.horizontal, 40.0)
            Spacer()
        }
    }
}

struct MyTextField: UIViewRepresentable {
    @Binding var currentText: String
    @Binding var placeHolder: String
    
    func makeUIView(context: Context) -> UITextField {
        let textField = UITextField()
        textField.inputView = UIView() // hiding keyboard
        textField.inputAccessoryView = UIView() // hiding keyboard toolbar
        textField.placeholder = placeHolder
        textField.textColor = UIColor.black
        textField.font = UIFont.systemFont(ofSize: 22.0)
        textField.delegate = context.coordinator
        return textField
    }
    
    func updateUIView(_ textField: UITextField, context: Context) {
        textField.text = currentText
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(text: $currentText)
    }
    
    class Coordinator: NSObject, UITextFieldDelegate {
        @Binding var text: String
        init(text: Binding<String>) {
            self._text = text
        }
    }
}

Reference: Prevent Keyboard from appearing when tapping on UITextField

Sign up to request clarification or add additional context in comments.

Comments

1

if you already have a TextField setup, you can add .disabled(true), this will stop the keyboard from showing up.

TextField("", text: $txt)
   .disabled(true)  // <--- here

1 Comment

Thanks. Fixed the default keyboard popping up when using a custom keyboard.

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.