3

I have a master detail application I'm working on in SwiftUI but once on the 1st DetailView, NavigationLink in the NavBar no longer works. I wrote this as a simple demonstration:

struct NavView: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: Layer()) {Text("Go to Layer 1")}
        }
    }
}

struct Layer: View {
    var body: some View {
        Text("Welcome to Layer 1")
            .navigationBarItems(trailing: NavigationLink(destination: AnotherLayer()) { Text("Go to Layer 2") })
    }
}

struct AnotherLayer: View {
    var body: some View {
        Text("Welcome to Layer 2")
    }
}

Everything renders and you can tap the navigationBarItem in Layer but nothing happens.

What's going on here? How can I access AnotherLayer?

Brandon Bradley
  • 3,160
  • 4
  • 22
  • 39

1 Answers1

2

A NavigationLink used as a navigationBarItem will not work no matter if you use it in the first or second level but a NavigationDestinationLink would solve the problem.

import SwiftUI

struct TestSwift: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: Layer()) {Text("Go to Level")}
        }
    }
}

struct Layer: View {
   let detailView = NavigationDestinationLink(AnotherLayer())

    var body: some View {
        VStack {
           Text("Text")

        }
        .navigationBarItems(trailing:
            Button(action: {
                self.detailView.presented?.value = true
            }, label: {
                Text("Present Now!")
            })
        )
    }
}

struct AnotherLayer: View {

    var body: some View {
        Text("Hello")
    }
}
Marc T.
  • 5,090
  • 1
  • 23
  • 40
  • Note that `NavigationDestinationLink` is deprecated. See [here](https://stackoverflow.com/questions/57273717/swiftui-navigationdestinationlink-deprecated) for a discussion about this. – Greg Sadetsky Sep 03 '20 at 14:34