Home > Mobile >  How can I show the keyboard while a context menu is open?
How can I show the keyboard while a context menu is open?

Time:08-25

When opening a context menu, the keyboard disappears and the active textfield will become unfocused. Is there a way to keep the keyboard open and the active textfield focused?

This short example demonstrates the issue:

struct ContentView: View {
    @State private var text: String = ""
    
    var body: some View {
        TextField(
            "Enter text",
            text: $text
        )
        .contextMenu {
            Button(action: {
                print("Hello")
            }) {
                Text("Hello")
            }
        }
    }
}

Before opening the context menu the keyboard is open and the text field is focused: Before opening context menu

After opening the context menu the keyboard is closed and the textfield becomes unfocused: After opening context menu

CodePudding user response:

You need to put FocusState in a onAppear inside of a DispatchQueue.main.asyncAfter(deadline: .now() 0.5) {}

This solves the problem:

struct ContentView: View {
    @FocusState private var focusOn: Bool
    @State private var text = ""

    var body: some View {
        TextField("Enter text", text: $text)
            .disableAutocorrection(true)
            .keyboardType(.default)
            .focused($focusOn)
            .padding()
            .contextMenu {
                Button {
                    print("Hello")
                } label: { Text("Hello") }
            }
            .onAppear {
                DispatchQueue.main.asyncAfter(deadline: .now()   0.5) {
                    focusOn = true
                }
            }
            .submitLabel(.go)
            .toolbar {
                ToolbarItem(placement: .keyboard) {
                    Button { hideKeyboard() } label: {
                        Image(systemName: "keyboard.chevron.compact.down")
                            .padding()
                    }
                }
            }
        }

        public func hideKeyboard() {
            UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
        }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
}
  • Related