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
3
  • 1
    Can you call the function in onAppear in your RestaurantView? Commented Oct 30, 2020 at 1:49
  • Does this answer your question: stackoverflow.com/a/58898046/12299030? Commented Oct 30, 2020 at 3: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. Commented Nov 2, 2020 at 22:57

1 Answer 1

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") } } 
Sign up to request clarification or add additional context in comments.

3 Comments

Unfortunately it still doesn't work. The function gets called, but the destination view is not shown.
@DanieleB I just tried it works, could you just replace your RestaurantView and RestaurantRow with Text only and remove the onTapGesture try again?
I tried that too, but it doesn't work. myFunction gets fired, but the destination isn't displayed

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.