NavigationStackView with .searchable modifier is working as expected.
struct NavStackListSearchView: View {
@State private var items = ["Item1", "Item2", "Item3", "Item4", "Item5"]
@State private var selectedItems: Set<String> = []
@State private var searchText: String = ""
var filteredItems: [String] {
if searchText.isEmpty {
return items
} else {
return items.filter { $0.contains(searchText) }
}
}
var body: some View {
NavigationStack {
List(selection: $selectedItems) {
ForEach(filteredItems, id: \.self) { item in
NavigationLink(item) {
Text(item).font(.title3)
}
}
}
}
.searchable(text: $searchText)
.onChange(of: searchText) { _ in
selectedItems = []
}
}
}
But NavigationSplitView with .searchable modifier is crashing:
struct NavSplitListSearchView: View {
@State private var items = ["Item1", "Item2", "Item3", "Item4", "Item5"]
@State private var selectedItems: Set<String> = []
@State private var searchText: String = ""
var filteredItems: [String] {
if searchText.isEmpty {
return items
} else {
return items.filter { $0.contains(searchText) }
}
}
var body: some View {
NavigationSplitView {
List(selection: $selectedItems) {
ForEach(filteredItems, id: \.self) { item in
Text(item)
}
}
} detail: {
if selectedItems.isEmpty {
Text("Pick an item")
} else {
Text("\(selectedItems.first ?? "--no item--")")
}
}
.searchable(text: $searchText)
.onChange(of: searchText) { _ in
selectedItems = []
}
}
}
To reproduce the crash in NavSplitView:
- launch the app
- click on "Item3"
- go back (if in compact mode)
- search for "3"
- click on only item shown, that is "Item3"
--> crash
Seems to be an issue with the index into the List/ForEach? But I see no way of influencing/double checking on that index. A change of filteredItems based on searchText should be recognised by SwiftUI as it is based on @State property items.
What do I miss? How can I solve this issue? Target iOS 16.2, Xcode 14.2