.searchable modifier with a keyboard shortcut

Hi,

Does anyone knows if it is possible (or there are plans) to enable associating a .searchable modifier with a keyboard shortcut?

It seems a no brainer and very useful for iPadOS or Catalyst.

Thanks

You can manually enable and disable searching and then link this up with your own keyboard shortcut. You just need to toggle the isSearching environment value. There is also a dismissSearch method in the environment if you prefer to dismiss the search like that.

Unfortunately .isSearching is read-only, it cannot me mutated.

If you try you get: Cannot assign to property: 'isSearching' is a get-only error.

Best regards

Same issue here, trying to implement Cmd+F keyboard shortcut for starting the search on a macOS app.

@colalo For iPadOS or Catalyst there seems to be an workaround based on SwiftUI-Introspect, see this answer on SO: https://stackoverflow.com/a/69308041/3451975

But for macOS, there's currently no solution. It would be great if the @Environment(\.isSearching) would be settable, then I could write a hidden button like this:

Button("Search") { isSearching = true }.keyboardShortcut("F").hidden()

Alternatively, the searchable() modifier could return a specific type (not some View) that supports keyboardShortcut, then the code would look something like this:

myView.searchable(text: $searchText).keyboardShortcut("F")

I ended up getting the following to work on macOS using the .searchable() modifier (only tested on macOS 12.3):

import SwiftUI

@main
struct MyApp: App {

    @State var searchText = ""
    var items = ["Item 1", "Item 2", "Item 3"]
    var searchResults: [String] {
        if searchText.isEmpty {
            return items
        } else {
            return items.filter { $0.contains(searchText) }
        }
    }

    var body: some Scene {
        WindowGroup {
            List(self.searchResults, id: \.self) { item in
                Text(item)
            }.searchable(text: self.$searchText)
        }.commands {
            CommandMenu("Find") {
                Button("Find") {
                    if let toolbar = NSApp.keyWindow?.toolbar,
                        let search = toolbar.items.first(where: { $0.itemIdentifier.rawValue == "com.apple.SwiftUI.search" }) as? NSSearchToolbarItem {
                        search.beginSearchInteraction()
                    }
                }.keyboardShortcut("f", modifiers: .command)
            }
        }
    }
}
.searchable modifier with a keyboard shortcut
 
 
Q