I have a View with a search button in the toolbar. The search button presents a sheet to the user and when he clicks on a result I would like the sheet to be dismissed and a detailView to be opened rather than navigating to the detailView from inside the sheet. The dismiss part is easy, but how do I open the detailView in the NavigationStack relative to the original View that presented the Sheet?
How to dismiss a Sheet and open a NavigationLink in a new View?
It's quite difficult to understand what is happening if you don't, at least, provide some code alongside your explanation. It then wouldn't require us to guess what your current situation looks like.
Here's something that works using example data (according to my interpretation of your question):
struct ContentView: View {
@State private var path: [Int] = []
@State private var showingSheet = false
var body: some View {
// use the path of the NavigationStack to allow for programmatic navigation
NavigationStack(path: $path) {
Text("Hello, World!")
.navigationDestination(for: Int.self) { num in
Text("Detail \(num)")
}
.toolbar {
Button("Search") {
showingSheet = true
}
}
.sheet(isPresented: $showingSheet) {
SearchView(path: $path)
}
}
}
}
struct SearchView: View {
@Environment(\.dismiss) private var dismiss
@Binding var path: [Int]
var body: some View {
List(1...10, id: \.self) { num in
Button("Option \(num)") {
// dismiss the sheet and then navigate to the selection's corresponding detail view
dismiss()
path.append(num)
}
}
}
}