1

I would like to call a function, after clicking on an item, and before displaying the destination view.

The code below doesn't seem to work: myFunction is called, but the destination view is not shown.

It looks like the onTapGesture overwrites the NavigationLink destination.

NavigationView {
    List(restaurants) { restaurant in
        NavigationLink(destination: RestaurantView(restaurant: restaurant)) {
            RestaurantRow(restaurant: restaurant)
        }.onTapGesture { myModel.myFunction(restaurant) }
    }
}

How can I have both, when clicking on a list item?

  • function is called
  • destination view is shown
Daniele B
  • 19,801
  • 29
  • 115
  • 173
  • 1
    Can you call the function in `onAppear` in your `RestaurantView`? – Paulw11 Oct 30 '20 at 01:49
  • Does this answer your question: https://stackoverflow.com/a/58898046/12299030? – Asperi Oct 30 '20 at 03:53
  • @Paulw11 thanks! eventually, it looks like the best practice is to call `myFunction` onAppear of the RestaurantView. If you write an answer, I will set it as the accepted one. – Daniele B Nov 02 '20 at 22:57

1 Answers1

1

Try to add NavigationLink into a Button, like:

Button(action: {
    //Call here
    myModel.myFunction(restaurant)
}, label: {
    NavigationLink(destination: RestaurantView(restaurant: restaurant)) {
            RestaurantRow(restaurant: restaurant)
    }
})

EDIT pasted test code, try directly

 struct TestNavigationView: View {

    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: Text("Detail").onAppear() {
                    test()
                }) {
                    Text("Click")
                }
            }
        }

    }

    func test() {
        print("Hell0")
    }
}

another approach: (might not work if List there)

struct TestNavigationView: View {

    var body: some View {
        NavigationView {
            VStack {

                NavigationLink(destination: Text("Detail")) {
                    Text("Click")
                }.simultaneousGesture(TapGesture().onEnded{
                    test()
                })

            }
        }

    }

    func test() {
        print("Hell0")
    }
}
William Hu
  • 15,423
  • 11
  • 100
  • 121
  • Unfortunately it still doesn't work. The function gets called, but the destination view is not shown. – Daniele B Oct 30 '20 at 01:27
  • @DanieleB I just tried it works, could you just replace your `RestaurantView` and `RestaurantRow` with `Text` only and remove the `onTapGesture` try again? – William Hu Oct 30 '20 at 01:56
  • I tried that too, but it doesn't work. `myFunction` gets fired, but the destination isn't displayed – Daniele B Nov 02 '20 at 22:32