'How to know when SwiftUI keyboard search button tapped in .searchable search window

I am using the .searchable modifier in SwiftUI. Is there anyway to know when the user presses the search key on the keyboard? I know how to do this by using a UIViewRepresentable and searchController. I'm wondering if there is a SwiftUI way of doing it with the .searchable modifier



Solution 1:[1]

This is still beta in macOS 12 (but not i/iPad/tvOS 15) as I write this so not really for this forum, however...

searching has an instance property:

var isSearching: Bool { get }

which can be passed into a child view using:

@Environment(\.isSearching) var isSearching

and subsequently interrogated from that var

Look up the Apple documentation

Solution 2:[2]

Add an .onSubmit(of: .search) modifier. Like this:

    List {
        ForEach(results, id: \.self) { result in
           Text(result)
        }
    }
    .searchable(text: $searchText)
    .onSubmit(of: .search) {
     // Search button tapped. Perform operation here
    }

If if works for you, mark as correct answer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 andrewbuilder
Solution 2 Victor