swiftuiswiftui-navigationlink

NavigationLink detail view transition only animates once


Problem:
Detail view transition only animates the first time

enter image description here

Workaround:
Make the LazyVStack a VStack. But this is not desirable.

Code:

struct TestView: View {
    var body: some View {
        NavigationView {
            ScrollView {
                VStack(alignment: .leading, spacing: 0) {
                    ForEach([1,2,3,4,5,6], id: \.self) { rowId in
                        NavigationLink {
                            Text("Got here!")
                        } label: {
                            Text("Row \(rowId)")
                                .padding()
                        }
                    }
                }
            }
        }
    }
}

#Preview {
    TestView()
}

Request:
Anyone know how to make the transition animation work every time?


Solution

  • In my tests, this problem is only happening with iOS 18. It works fine with iOS 15, 16 and 17.

    Fortunately, it works on iOS 18 when you use a NavigationStack instead of the (now deprecated) NavigationView. It also works on iOS 16 and 17 when a NavigationStack is used. So it's only iOS 15 that still needs to use NavigationView.

    Since you are using a form of NavigationLink that is also valid for iOS 18 (in other words, not deprecated), you just need to switch between using a NavigationView for iOS 15 and NavigationStack for later iOS versions:

    private var mainContent: some View {
        ScrollView {
            // content as before
        }
    }
    
    var body: some View {
        if #available(iOS 16.0, *) {
            NavigationStack {
                mainContent
            }
        } else {
            NavigationView {
                mainContent
            }
        }
    }
    

    If you would be using other forms of NavigationLink that have become deprecated, such as for programmatic navigation, the migration to using a NavigationStack may be a bit more complicated. See this answer for one way to approach the migration (it was my answer).