Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting of several NavigationLink in a NavigationStack causes the loss of animation and breaks the backtracking

Tags:

swift

swiftui

SwiftUI 4.0 introduces a new NavigationStack view.

Let's consider this simple structure.

struct Item: Identifiable, Hashable {
    static let sample = [Item(), Item(), Item()]
    let id = UUID()
}

When a NavigationLink is nested in another one, the navigation loses its animation and the backtracking takes directly to the root. Did I miss something, or is this a bug?

struct ItemDetailView: View {
    let item: Item
    
    var body: some View {
        Text(item.id.uuidString)
    }
}

struct ItemListView: View {
    var body: some View {
        List(Item.sample) { item in
            NavigationLink(item.id.uuidString, value: item)
        }
    }
}

struct ExploreView: View {
    var body: some View {
        List {
            Section {
                NavigationLink {
                    ItemListView()
                } label: {
                    Text("Items")
                }
            }
        }
        .navigationTitle("Explore")
        .navigationDestination(for: Item.self) { item in
            ItemDetailView(item: item)
        }
    }
}

struct ContentView: View {
    var body: some View {
        NavigationStack {
            ExploreView()
        }
    }
}

Thanks!

like image 854
parapote Avatar asked Dec 06 '25 07:12

parapote


1 Answers

Found the solution thanks to @Asperi's comment.

First, create a Hashable enum containing the destinations.

enum Destination: Hashable {
    case items
    
    var view: some View {
        switch self {
        case .items:
            return ItemListView()
        }
    }
    
    var title: LocalizedStringKey {
        switch self {
        case .items:
            return "Items"
        }
    }
}

Next, use the new NavigationLink initializer.

NavigationLink(Destination.items.title, value: Destination.items)

And finally, add a new .navigationDestination modifier to catch all Destination values.

.navigationDestination(for: Destination.self) { destination in
    destination.view
}
like image 181
parapote Avatar answered Dec 08 '25 21:12

parapote



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!