Post

Replies

Boosts

Views

Activity

Reply to Issue with SwiftUI NavigationStack, Searchable Modifier, and Returning to Root View
I'm having this issue on the app I'm developing, one way that I found to fix it was wrapping the view that had the searchable with a NavigationView So I've made this small playground code that cannot pop to root when search is active. import SwiftUI import PlaygroundSupport struct RootView: View { @State private var path = NavigationPath() var body: some View { NavigationStack(path: $path) { DetailView( number: 0, popToRoot: { path = NavigationPath() } ) .navigationDestination(for: Int.self) { i in DetailView( number: i, popToRoot: { path = NavigationPath() } ) } } } } struct DetailView: View { var number: Int var popToRoot: () -> Void @State var search = "" var body: some View { VStack { NavigationLink("Go to Random Number", value: Int.random(in: 1...1000)) Button("Go to root") { popToRoot() } } .navigationTitle("Number: \(number)") .searchable(text: $search, prompt: "Search") } } PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.setLiveView(RootView()) When I wrap it with NavigationView I can activate the search without having the pop to root issue. import SwiftUI import PlaygroundSupport struct RootView: View { @State private var path = NavigationPath() var body: some View { NavigationStack(path: $path) { DetailView( number: 0, pop: nil, popToRoot: { path = NavigationPath() } ) .navigationDestination(for: Int.self) { i in DetailView( number: i, pop: { path.removeLast() }, popToRoot: { path = NavigationPath() } ) } } } } struct DetailView: View { var number: Int var pop: (() -> Void)? var popToRoot: () -> Void @State var search = "" var body: some View { // Add this NavigationView with navigation bar hidden NavigationView { VStack { NavigationLink("Go to Random Number", value: Int.random(in: 1...1000)) Button("Go to root") { popToRoot() } } .toolbar { // Programatically add a back button since navigation view bar is hidden if pop != nil { ToolbarItem(placement: .navigation) { Button("Back", systemImage: "chevron.backward") { pop?() } .buttonStyle(.borderless) .labelStyle(.titleAndIcon) .fixedSize() } } } .navigationTitle("Number: \(number)") .searchable(text: $search, prompt: "Search") }.navigationBarHidden(true) } } PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.setLiveView(RootView()) It definitely shouldn't be the way to fix this, but it's an okayish workaround to fix it for now...
Nov ’24