I'm trying to create a search screen with a text field, but I can't make it so that when entering the screen, it immediately appears with the keyboard and the focus on the text field. I've tried using the .focused(focused) modifier, changing the variable with .onAppear and .onChanged so that the keyboard is always shown and the focus is on the text field, but then the keyboard starts to blink. Is there any way to always show the keyboard in SwiftUI?

I changed the variable focused to true in the .onAppear method and also set this variable to true in the .onChanged(focused) { state in } to keep the focus on the text field all the time and have the keyboard on the screen. However, in this case, the keyboard blinks.

I also tried to create a custom text field, but it didn't work either. Here is the code:

struct TextFieldPermanentKeyboard: UIViewRepresentable {
    var placeholder: String
    @Binding var text: String
    var onCommit: () -> Void
    
    final class Coordinator: NSObject, UITextFieldDelegate {
        var parent: TextFieldPermanentKeyboard
        
        init(_ parent: TextFieldPermanentKeyboard) {
            self.parent = parent
        }
        
        @objc func onCommit() {
            self.parent.onCommit()
        }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    func makeUIView(context: Context) -> UITextField {
        let textfield = UITextField()
        textfield.delegate = context.coordinator
        textfield.placeholder = self.placeholder
        textfield.becomeFirstResponder()
        textfield.addTarget(
            context.coordinator,
            action: #selector(context.coordinator.onCommit),
            for: .editingDidEndOnExit
        )

        return textfield
    }
    
    func updateUIView(_ uiView: UITextField, context: Context) {
        uiView.text = text
        
        if !uiView.isFirstResponder {
            uiView.becomeFirstResponder()
        }
    }
}
0

There are 0 best solutions below