SwiftUI: navigationBarItems missing on first render

164 Views Asked by At

I'm seeing a strange issue that I was able to reproduce with a small sample. If you have a detail view that has navigationBarItems set, and that detail is the second view pushed on a navigation stack, the items do not show up when you get to the detail page. Here is the sample:

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: MiddleTestView()) {
                    Text("Push View")
                }
            }
        }
    }
}

struct MiddleTestView: View {
    var body: some View {
        VStack {
            NavigationLink(destination: TestView()) {
                Text("Push Another View")
            }
        }
    }
}

struct TestView: View {
    var body: some View {
        VStack {
            Text("Testing 1, 2, 3")
        }
        .navigationBarItems(leading: Button("Test") { print("pressed") })
    }
}

If anything causes the TestView to re-render, then the button will show, for instance if the TestView does this:

struct TestView: View {
    @State var hasChanges = false
    var body: some View {
        VStack {
            Text("Testing 1, 2, 3")
            Button("Toggle") { hasChanges = !hasChanges }
        }
        .navigationBarItems(leading: Button(hasChanges ? "Test1" : "Test2") { print("pressed") })
    }
}

Then pressing the "Toggle" button once will cause the navigationBarItems to appear, and they will stay there until the view is dismissed. Additionally, if the TestView is shown first, instead of the MiddleTestView, then there is no problem with the navigationBarItems. I cannot see any reason for this behavior, it seems like a pretty glaring bug that makes working with navigation stacks in SwiftUI fundamentally broken, unless I'm missing something. Does anyone have any insight into what is going on here or how to get around it?

0

There are 0 best solutions below