I am using NavigationView with three columns: Sidebar, Search & Detail. When a search result in the middle column is selected on the iPad (where search and detail are displayed side by side) and then disappears from the list due to the search term changing, the app crashes with EXC_BREAKPOINT.
The problem is reproducible with the following simple demo app.
- Search "table"
- Select "Table"
- Search "chair"
- App crashes
//
// ThreeColumnSearchTestApp.swift
//
import SwiftUI
@main
struct ThreeColumnSearchTestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
var body: some View {
NavigationView {
Sidebar()
Search()
Detail()
}
}
}
struct Sidebar: View {
var body: some View {
NavigationLink(destination: Search()) {
Text("List")
}
}
}
struct Search: View {
@StateObject var model = SearchModel()
@State var searchText = ""
var body: some View {
List(model.searchResults, id: \.self) { value in
NavigationLink(destination: Detail(value: value)) {
Text(value)
}
}
.searchable(text: $searchText)
.onChange(of: searchText) { newValue in
model.searchResults = model.values.filter({ value in
value.contains(searchText)
})
}
}
}
class SearchModel: ObservableObject {
var values = ["Table", "Chair", "Floor"]
var searchResults = [String]()
}
struct Detail: View {
var value: String?
var body: some View {
Text(value ?? "No Selection")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Am I doing something wrong or is this a bug? Any workarounds?
PS: I know iOS 16 introduces a new way to do this. I didn't test if the problem occurs there as well, I want to support iOS 15.