NavigationLink in the Page TabView works with an error

Viewed 72

Here is the code i am trying to reproduce. The problem is that when you click on the link, the screen opens without animation and an error is generated in the console. But if you go to another page Tab and go back, then everything works correctly.

var body: some View {
    TabView {
        //First Screen
        NavigationView {
            NavigationLink {
                Text("Hello Page 1")
            } label: {
                Text("Page 1")
            }
        }
        .navigationViewStyle(.stack)
        .tag(1)

        //Second Screen
        NavigationView {
            NavigationLink {
                Text("Hello Page 2")
            } label: {
                Text("Page 2")
                    .foregroundColor(.green)
            }
        }
        .navigationViewStyle(.stack)
        .tag(2)
    }
    .tabViewStyle(.page(indexDisplayMode: .always))
}
1 Answers

To correct this error you need to use individual structs in your TabView. In a real app, you would be doing this as a matter of course, and would not ever see this error. An example would be:

struct MyTabView: View {
    var body: some View {
            TabView {
                Content1()
                    .tag(1)

                Content2()
                    .tag(2)
            }
            .tabViewStyle(.page(indexDisplayMode: .always))
    }
}

struct Content1: View {
    var body: some View {
        NavigationView {
            NavigationLink {
                Text("Hello Page 1")
            } label: {
                Text("Page 1")
            }
        }
        .navigationViewStyle(.stack)
    }
}

struct Content2: View {
    var body: some View {
        NavigationView {
            NavigationLink {
                Text("Hello Page 2")
            } label: {
                Text("Page 2")
            }
        }
        .navigationViewStyle(.stack)
    }
}

NavigationView would go in each of these contained structs as they would be the top of the hierarchy for each tab.

Related