0

I want the code to work when I tap on the NavigationLink displayed in the List.

Look at this code. When I tap on Text("Favorite"), the code moves.

But when I tap the List, code doesn't work.

I set onTapesture on NavigationLink itself, but that didn't solve the problem

How can we fix this?

var body: some View {
        NavigationView{
            List{
                NavigationLink(destination: DeliveryServiceList().environmentObject(self.userData)){
                    Text("Favorite")
                    }.onTapGesture {
                         self.userData.showFavoritesOnly.toggle()
                    }
            }.navigationBarTitle(Text("Services"))
        }
    }
enpipi
  • 11

1 Answers1

0

To achieve what you ask do this:

var body: some View {
    NavigationView() {
        List {
            NavigationLink(destination: DeliveryServiceList().environmentObject(self.userData)) {
                Text("Favorite")
            }
        }
    }.navigationBarTitle(Text("Services"))
}
}

and move "self.userData.showFavoritesOnly.toggle()" to the "DeliveryServiceList()", since you already do ".environmentObject(self.userData)"

In "DeliveryServiceList" do something like:

 .onAppear {
     self.userData.showFavoritesOnly.toggle()
 }

You can also do this, if you really want to use onTapGesture: (from: How could I do something before navigate to other view by NavigationLink?)

@State var isPresented = false

var body: some View {
    NavigationView {
        List {
            NavigationLink(destination: DeliveryServiceList().environmentObject(self.userData)), isActive: $isPresented) {
                Text("Favorite")
                    .onTapGesture {
                        self.userData.showFavoritesOnly.toggle()
                        self.isPresented = true
                }
            }
            .navigationBarTitle("Services")
        }
    }
}
  • Thank you. I tried, but it didn't solve the problem. I tapped the Text in the list and it worked, but tapping anything other than the text area didn't activate onTapGesture. – enpipi Jun 17 '20 at 18:29