Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a ContextMenu with a NavigationLink?

I have a NavigationLink with an attached .contextMenu modifier. Note that the NavigationLink is inside of a ForEach which is inside of a LazyHStack which is inside of a ScrollView. (I'm creating a horizontal scrolling row of "cards", much like many Apple apps.)

Now, both the navigation and the context menu work; if I single-tap, it navigates to the view I specify and if I long-press it presents a context menu. The issue is that the context menu is focused on a highlighted grey view due to the navigation link highlighting.

Screenshot of issue

I considered removing the highlighting of the navigation link via a view modifier to no avail. The grey highlight still applies to the context menu view.

.onAppear {
    UITableViewCell.appearance().selectionStyle = .none
    UITableView.appearance().allowsSelection = false
}

So, how can I have a view that is both navigatable on tap as well as presents a context menu focused on the view when a long-press gesture is triggered? Note that I am not trying to have a NavigationLink inside a ContextMenu (as many questions seem to be asking); I am trying to have a ContextMenu attached to a NavigationLink.

like image 226
user1234 Avatar asked Oct 18 '25 14:10

user1234


1 Answers

By provided description I assume the solution will be to activate NavigationLink programmatically on tap, like (pseudo-code):

Card()
  .onTapGesture {
     activeCard = item
  }
  .contextMenu {
     // ...
  }
  .background(
     NavigationLink(destination: SomeView(), tag: item, selection: $activeCard) {
       EmptyView()
     }
  )

See next for complete example https://stackoverflow.com/a/58898046/12299030.

like image 170
Asperi Avatar answered Oct 21 '25 02:10

Asperi