Search code examples
swiftmacosswiftuisearchable

SwiftUI macOS searchable keyboard navigation


Having search suggestion

        .searchable(text: $searchText, placement: .toolbar) {
            List {
                Text("Search suggestion 1").searchCompletion("Hello")
                Text("Search suggestion 2").searchCompletion("Hello 2")
            }.listStyle(.sidebar)
        }

How to enable keyboard Up/Down navigation between suggestion like in Finder

Even the mouse selection doesn't do anything

enter image description here?


Solution

  • the key was to use Section and Labels with the .searchCompletion, all works great (keyboard, completion...)

    the results can also be calculated on the flight as demonstrated

        .searchable(text: $searchText, placement: .toolbar) {
            if searchText.count == 0 {
                Section("Fonts") {
                    Label("Font family A", systemImage: "textformat").searchCompletion("familyA")
                    Label("Font family B", systemImage: "textformat").searchCompletion("familyB")
                }
                Divider()
                Section("Foundries") {
                    Label("Foundry A", systemImage: "briefcase").searchCompletion("foundry:A")
                    Label("Foundry B", systemImage: "briefcase").searchCompletion("foundry:B")
                }
                Divider()
                Section("Designers") {
                    Label("Author 1", systemImage: "person").searchCompletion("author:A")
                    Label("Author 2", systemImage: "person").searchCompletion("author:B")
                }
                Divider()
                Section("Keywords") {
                    Label("Keyword 1", systemImage: "tag").searchCompletion("tag:A")
                    Label("Keyword 2", systemImage: "tag").searchCompletion("tag:B")
                }
                Divider()
                Section("Letters") {
                    Label("N", systemImage: "textformat.size.larger").searchCompletion("letter:A")
                }
            } else {
                Section("Keywords") {
                    Text("X").searchCompletion("Hello")
                }
            }
        }
    

    enter image description here