0
votes

My need is simple but I can't seem to figure a way (and many posts are rather complicated or are old/for iOS).

I have a NavigationView with NavigationLink and it all works fine. For certain reasons, I'd like to know the item the user clicked on because it's used for other actions on the view.

I tried putting a button inside the NavigationView but then only the button action fires, but the link doesn't work.

I tried OnTapGesture - then the function fires but isn't propagated so the detail view never shows up.

What am I missing? Is there some way I can do this without overcomplicating?

ForEach(anArray, id: \.self) { entry in
    NavigationLink(destination: SettingsView(s: entry)
    {
         Text("something")
    }.onTapGesture {print("Hello")}
}

1

1 Answers

1
votes

Here is the solution, actually use a button that does some action and activates a link

Tested with Xcode 11.5b2

   @State private var activatedLink: Int? = nil

   // ... other code

   ForEach(Array(anArray.enumerated()), id: \.element) { (i, entry) in
        Button("something") {
            print(">> some action")

            self.activatedLink = i   // << order might be important !!
        }.background(
            NavigationLink(destination: SettingsView(s: entry), tag: i, selection: $activatedLink) { EmptyView() }
               .buttonStyle(PlainButtonStyle()) // << required !!
        )
   }