SwiftUI: Solution to NavigationLink unexpected pop back to previous screen

Did you know that there is a bug in SwiftUI (as at the writing of this post) that sometimes causes a view to automatically navigate back to a previous view?

I ran into this issue a number of times wondering why I would navigate to a second view and it would pop back immediately to the first view, just on its own.

After some research, I found out that this occurs mostly when you have EXACTLY two NavigationLink in your view. How so? Not sure why, maybe Apple Engineers can answer that, but that is the case.

Solution

Until the bug is fixed in subsequent releases, it becomes safe to either reduce the number of NavigationLink in a view to one or increase it beyond two.

To increase the number of NavigationLinks without worrying about navigating to a particular view, you can make sure of EmptyView, as shown below.

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack(spacing: 16) {
                NavigationLink(destination: Screen2View()) {
                    Text("Go To Screen 2")
                        .foregroundColor(Color.white)
                        .padding()
                        .background(
                            RoundedRectangle(cornerRadius: 5)
                                        .fill(Color.blue)
                        )
                }

                NavigationLink(destination: Screen3View()) {
                    Text("Go To Screen 3")
                        .foregroundColor(Color.white)
                        .padding()
                        .background(
                            RoundedRectangle(cornerRadius: 5)
                                        .fill(Color.red)
                        )
                }

                NavigationLink(destination: EmptyView()) { // <---- Here
                    EmptyView()
                }
            }
        }
    }
}

Applying the trick above should help you fix the pop behaviour.


You can also check out this thread for more cases of this weird behaviour that different people have experienced.

Comment down below to let me know if this fix works for you. Cheers!