In my app I provide search functionality. When submitting the search query a request is sent to the backend and the results are displayed. While a user is typing their query the search text is sent to the backend and search suggestions are returned. If a user taps on one of the search suggestions I want to execute that search and stop displaying the search suggestions so the user can see the results. I’ve tried clearing the search suggestions on tap, but they keep displaying. Dismissing the search with by calling dismissSearch
also doesn’t work. For some reason the .onSubmit
gets called when a search suggestion button is tapped.
struct SearchView: View {
@State private var searchText = ""
@State private var searchScope = SearchScope.anything
@State private var searchSuggestions = [SearchSuggestion]()
@State private var searchResults = [SearchResult]()
var body: some View {
VStack {
if !searchResults.isEmpty {
ForEach(searchResults, id: .self) { result in
Text(result.value)
}
}
}
.searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always))
.searchSuggestions({
ForEach(searchSuggestions, id: .self) {
Button("(suggestion.value)") {
searchText = suggestion.term
runSearch()
}
}
})
.searchScopes($searchScope, activation: .onSearchPresentation, {
ForEach(SearchScope.allCases, id: .self) { scope in
Text(scope.rawValue.capitalized).tag(scope)
}
})
.onSubmit(of: .search, runSearch)
.onChange(of: searchScope) {
runSearch()
Task {
await runSearchSuggestions()
}
}
.onChange(of: searchText) {
Task {
await runSearchSuggestions()
}
}
}
}
The best solution I could come up with is introducing a showSearchSuggestions
state variable. It is true
by default and gets set to false
when a search is executed. In the ForEach
it is checked to determine if the search suggestions should be shown. This works once, after a search suggestion has been tapped the results are shown, but then no suggestions are shown after that as the variable is never set to true
again. I’ve tried to set showSearchSuggestions
to true
by using the isSearching
environment variable, but that can only be accessed from the searched view?