alionthego
alionthego

Reputation: 9773

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

Upvotes: 4

Views: 2009

Answers (2)

Victor
Victor

Reputation: 359

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.

Upvotes: 8

andrewbuilder
andrewbuilder

Reputation: 3799

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

Upvotes: 1

Related Questions