Search code examples
swiftuiswiftui-navigationlink

SwiftUI NavigationLink


I'm working on a SwiftUI practice app and I ran into an issue with the NavigationView/NavigationLink. I am currently using the Metropolitan Museum of Art API and I wanted to make a list of departments that segues to another list of objects in that department, then that list segues to the object's information. Currently the NavigationView/NavigationLink setup I have is creating multiple NavigationViews and is resulting in multiple back buttons/navigation bars. Is there a way to have the new NavigationView replace the old one or have them work in line with one another? The only way I know how to create a segue in SwiftUI is through a NavigationView/NavigationLink but creating it twice seems to be the wrong way to go about things. I have a screen shot of the current state of my app. App Image This is my code at the moment.

struct ContentView: View {

@ObservedObject var model = DepartmentListViewModel()

var body: some View {
    NavigationView {
        List {
            ForEach(model.departments, id: \.self) { department in
                NavigationLink(destination: DetailView(viewModel: DetailListViewModel(selectedDepartment: department))) {
                    Text(department.displayName)
                }
            }
        }
        .navigationBarTitle("Departments")
    }
}
}
struct DetailView: View {
@ObservedObject var viewModel: DetailListViewModel

init(viewModel: DetailListViewModel) {
    self.viewModel = viewModel
}

var body: some View {
  NavigationView {
      List {
        ForEach(viewModel.objects, id: \.self) { object in
            NavigationLink(destination: ObjectView(viewModel: ObjectListViewModel(selectedObject: object))) {
                Text(String(object))
            }
          }
      }
      .navigationBarTitle("ObjectIDs")
  }
}
}

Solution

  • You don't need NavigationView in your DetailView anymore, the first one handle it