6

I use the SwiftUI searchable of iOS15 modifier to make a search with the onSubmit modifier to send a HTTP request, and I also would like to reset the initial list when the user tap on Cancel button; I would appreciated if I had found an onCancel modifier. Is anyone that soled this?

Beppex
  • 123
  • 1
  • 6

1 Answers1

9

We have two environment values coming with .searchable, which are isSearching, and dismissSearch.

@Environment(\.isSearching) private var isSearching: Bool
@Environment(\.dismissSearch) private var dismissSearch

If we have our searchable code like the below

.searchable(text: self.$searchText)

Then we can detect the search being cancelled like the below snippet.

.onSubmit(of: .search) {
    //Search triggered on tap of search button in keyboard
}
.onChange(of: searchText) { value in
    if searchText.isEmpty && !isSearching {
        //Search cancelled here
    }
}

Try using this approach meanwhile apple hopefully comes up with some .onCancel(.search) modifier for us in the upcoming releases.

Ravi
  • 371
  • 6
  • 11