My goal is to have a search view in my app where users can search by entering a text and submitting it. While a user is typing I want to display search suggestions.
The on submit of the search text works. Suggestions are displayed as well while a user is typing, however, I don’t know how to perform a search when a suggestion is tapped. How can I achieve this?
Currently this is the search functionality (skeleton) of my search view.
struct SearchView: View {
@Bindable var viewData = SearchViewData()
var body: some View {
NavigationStack {
List {
ForEach(viewData.searchResults) { result in
Text(result.value)
}
}
}
.searchable(text: $viewData.searchText)
.onSubmit(of: .search, runSearch)
.searchSuggestions {
ForEach(viewData.suggestedSearches) { suggestion in
Text("(suggestion.term)").searchCompletion(suggestion)
}
}
.onChange(of: viewData.searchText) {
fetchSearchSuggestions()
}
}
func runSearch() {
await viewData.runSearch() // The suggestedSearches gets cleared so they arent displayed anymore
}
func fetchSearchSuggestions() {
if !viewData.searchText.empty {
Task {
await viewData.fetchSearchSuggestions()
}
}
}
}