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
Navigating to different data types using NavigationPath
structContentView:View{@Stateprivatevarpath=NavigationPath()varbody:someView{NavigationStack(path: $path){List{ForEach(0..<5){ i inNavigationLink("Select Number: \(i)", value: i)}ForEach(0..<5){ i inNavigationLink("Select String: \(i)", value:String(i))}}.toolbar{Button("Push 556"){
path.append(556)}Button("Push Hello"){
path.append("Hello")}}.navigationDestination(for:Int.self){ selection inText("You selected number \(selection)")}.navigationDestination(for:String.self){ selection inText("You selected string \(selection)")}}}}
How to make a NavigationStack return to its root view programmatically
import SwiftUI
structDetailView: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){ i inDetailView(number: i, path: $path)}}.onChange(of: path){ oldValue, newValue inprint(newValue)}}}
How to save NavigationStack paths using Codable
import SwiftUI
@ObservableclassPathStore{varpath:NavigationPath{
didSet {save()}}privateletsavePath=URL.documentsDirectory.appending(path:"SavedPath")init(){
if let data =try?Data(contentsOf: savePath){
if let decoded =try?JSONDecoder().decode(NavigationPath.CodableRepresentation.self,
from: data
){
path =NavigationPath(decoded)return}}
path =NavigationPath()}func save(){
guard let representation = path.codable else{return}do{letdata=try?JSONEncoder().encode(representation)try data?.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){ i inDetailView(number: i, path: $pathStore.path)}}}}
Customizing the navigation bar appearance
structContentView:View{varbody:someView{NavigationStack{List(0..<100){ i inText("Row \(i)")}.navigationTitle("Title goes here").navigationBarTitleDisplayMode(.inline).toolbarBackground(.blue).toolbarColorScheme(.dark).toolbar(.hidden, for:.navigationBar)}}}