NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

SOLVED: How to detect right click on list in MacOS

Forums > SwiftUI

I am trying to use a context menu on a project that has a UI that looks like XCode. I want to be able to right click on the Navigator item (Sidebar item in my case) and have a context menu come up that allows for editing/modifying the item clicked on.

A couple issues, first is the context menu is shown, but I can not get the identity or a reference to the item clicked on.

I do not want to force the user to select an item to edit it - right clicking does not select the item in XCode and I prefer that mechanism.

I have seen several examples online (not many) that use the Section parameter of the List and those won't wort for several reasons, the first one being I don't want to make a selection, I want to leave the current selection alone and simply detect the right click and some how identify which row was right clicked. The follow does detect the riglth click and execute the action but I can not determine which row was right cliked.

My navigation bar/sidebar is organized like this (This is not the actual code, it is spread over multiple views.)

...

NavigationView {
    List() {
        Section {}
            ForEach(children) { child in
                    Section(header: Text(child.name))
                    {
                        OutlineGroup(child.children ?? [Sidebar](), children: \.children) { sidebar in
                            SidebarRowView(sidebar: sidebar, addSidebarItemShown: $addSidebarItemShown)
                            }
                    }
            }
      }
      .contextMenu {
             Button("Add to Pinned Sidebars") {  print("Right Click detected") }
      }
}

   

Waiting for WWDC to see if this changes, but at the moment ContextMenu is the only way to detect right clicks on MacOS in SwiftUI - it seems.

   

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.