0
NavigationView {
            List{
                ForEach(self.data.firebaseObj.lists, id: \.self) { item in
                    NavigationLink(
                        destination: DetailView(
                            list: item,
                            listIndex: self.data.firebaseObj.lists.firstIndex(of: item) ?? -1
                        ).environmentObject(self.data)
                    ){
                        Text(item.name)
                    }
                }
                .onDelete(perform: delete)
            }
            .navigationBarTitle(Text("Le liste").font(.largeTitle), displayMode: .inline)
            .navigationBarItems(
                leading: SignOutButton(),
                trailing: Button(action: {
                    self.show_modal = true
                }) {Image(systemName: "plus")}.sheet(isPresented: self.$show_modal) {
                    AddListForm(email: self.session.session!.email!).environmentObject(self.data)
            })
        }.onAppear(
            perform:{
                self.data.createList(username: self.session.session!.email!)

            })
        .onDisappear(
            perform: {
                self.data.listener.remove()
                print("should be removed")
            }) 

That's the code I have and, as written in the title, clicking on the NavigationLink doesn't trigger the .onDisappear() method. Instead, changing to another tab view works fine. Am I doing something wrong or is this just the way it is supposed to work? In the second case, is there a simple way to execute some code when clicking on a NavigationLink?

1 Answers1

0

This is how it is supposed to work, because your DetailView is a subview of your MainView if you use NavigationLink. That is why your MainView isn't really disappearing programmatically speaking.

Nevertheless you can do it like this:

struct ContentView: View {
    @State private var showDetailView = false

    var body: some View {
        NavigationView {
            VStack {

                NavigationLink(destination: DetailView(), isActive: $showDetailView) {

                    Button(action: {
                        print("should be removed")
                        self.showDetailView = true
                    }, label: {
                        Text("Listitem")
                    })

                }


                Spacer()

            }.navigationBarTitle(Text("MainView"))
        }
    }
}

struct DetailView: View {
    var body: some View {
        Text("DetailView")
    }
}
Kuhlemann
  • 3,066
  • 3
  • 14
  • 41
  • Thanks, I think that might have helped me even though I think it might be more useful to put the button inside the the navigation link instead of the EmptyView in my case.Do you think it'd be ok to do something like that ? – Guillaume Franzoni Darnois Apr 21 '20 at 11:32
  • Absolutely. I edited my post to represent your request. – Kuhlemann Apr 21 '20 at 12:45