I'm implementing autocomplete using .searchSuggestions
. Since my autocomplete needs communication with the server, I'm adding a separate state for autocomplete and change the state in .onChange(of: searchText)
. I want the suggestions be dismissed when any of them are tapped. This worked well on iOS 16.0, but not on iOS 16.4 and 16.5. On iOS 16.4, when a suggestion is tapped, it replaces the search text, but it also makes new suggestions, so the suggestions are not dismissed.
This difference does not appear when .searchSuggestions
does not depend on a separate state. Would there be any workarounds?
Here's the minimum reproducible example (modified from an example in https://www.hackingwithswift.com/quick-start/swiftui/how-to-add-a-search-bar-to-filter-your-data):
import SwiftUI
struct ContentView: View {
let names = ["Holly", "Josh", "Rhonda", "Ted"]
@State private var searchText = ""
@State private var searchResults = [String]()
var body: some View {
NavigationStack {
List {
ForEach(searchResults, id: \.self) { name in
NavigationLink {
Text(name)
} label: {
Text(name)
}
}
}
.navigationTitle("Contacts")
}
.onChange(of: searchText) { _ in
searchResults = names.map { $0 }
// In my app,
// Task {
// searchResults = await retrieveFromServer()
// }
}
.searchable(
text: $searchText,
placement: .navigationBarDrawer(displayMode: .always)
)
.searchSuggestions {
// ForEach(searchResultsComputed, id: \.self) works well on both versions
ForEach(searchResults, id: \.self) { result in
Text("Are you looking for \(result)?").searchCompletion(result)
}
}
}
var searchResultsComputed: [String] {
names.map { $0 }
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
and here's the result: https://youtu.be/1t4H6AT3y5A