Search code examples
swiftuikeyboardtextfielddisable

Swiftui - Disable Keyboard from showing up for TextField


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


Solution

  • 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