Search code examples
iosswiftswiftuiswiftui-navigationlink

Transition animation gone when presenting a NavigationLink in SwiftUI


I have a List with NavigationLinks.

List {
    ForEach(items, id: \.id) { item in
        NavigationLink(destination: ItemView(), tag: item.id, selection: self.$viewModel.selectedItemId) {
            Text("Some text")
        }
    }
    .onDelete(perform: delete)
}
.id(UUID())

And a corresponding ViewModel which stores the selected item's id.

class ViewModel: ObservableObject {
    @Published var selectedItemId: String? {
        didSet {
            if let itemId = selectedItemId {
                ...
            }
        }
    }
    ...
}

The problem is that when I use NavigationLink(destination:tag:selection:) the transition animation is gone - the child view pops up immediately. When I use NavigationLink(destination:) it works normally, but I can't use it because I need to perform some action when a NavigationLink is selected.

Why the transition animation is gone? Is this a problem with NavigationLink(destination:tag:selection:)?


Solution

  • It turned out to be a problem with .id(UUID()) at the end of the list. Removing it restores the transition animation:

    List {
        ForEach(items, id: \.id) { item in
            NavigationLink(destination: ItemView(), tag: item.id, selection: self.$viewModel.selectedItemId) {
                Text("Some text")
            }
        }
        .onDelete(perform: delete)
    }
    //.id(UUID()) <- removed this line
    

    I added this following this link How to fix slow List updates in SwiftUI. Looks like this hack messes up tags/selections when using NavigationLink(destination:tag:selection:).