You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
How to make a NavigationStack return to its root view programmatically
importSwiftUIstructDetailView:View{varnumber:Int
// @Binding var path: Int
@Bindingvarpath:NavigationPathvarbody:someView{NavigationLink("Go to Random Number",value:Int.random(in:1...1000)).navigationTitle("Number: \(number)").toolbar{Button("Home"){
// path.removeAll()
path=NavigationPath()}}}}structContentView:View{
// @State private var path = [Int]()
@Stateprivatevarpath=NavigationPath()varbody:someView{NavigationStack(path:$path){DetailView(number:0,path:$path).navigationDestination(for:Int.self){iinDetailView(number:i,path:$path)}}.onChange(of:path){oldValue,newValueinprint(newValue)}}}
How to save NavigationStack paths using Codable
importSwiftUI@ObservableclassPathStore{varpath:NavigationPath{didSet{save()}}privateletsavePath=URL.documentsDirectory.appending(path:"SavedPath")init(){ifletdata=try?Data(contentsOf:savePath){ifletdecoded=try?JSONDecoder().decode(NavigationPath.CodableRepresentation.self,from:data){path=NavigationPath(decoded)return}}path=NavigationPath()}funcsave(){guardletrepresentation=path.codableelse{return}do{letdata=try?JSONEncoder().encode(representation)trydata?.write(to:savePath)}catch{print("Failed to save navigation data")}}}structDetailView:View{varnumber:Int@Bindingvarpath:NavigationPathvarbody:someView{NavigationLink("Go to Random Number",value:Int.random(in:1...1000)).navigationTitle("Number: \(number)").toolbar{Button("Home"){path=NavigationPath()}}}}structContentView:View{@StateprivatevarpathStore=PathStore()varbody:someView{NavigationStack(path:$pathStore.path){DetailView(number:0,path:$pathStore.path).navigationDestination(for:Int.self){iinDetailView(number:i,path:$pathStore.path)}}}}