2

I want to tap a button and show a context menu in SwiftUI for a macOS app. I can see the button but when I tap the button nothing happens.

let menuItems = ContextMenu {
        Button("Today") {}
        Button("Tomorrow") {}
    }

 Button {
                    // action
                } label: {
                    Label("Add Date", systemImage: "calendar")
                        .contextMenu(menuItems)
                }

Any ideas?

enter image description here

2 Answers 2

4

It seems to me that you just look for menu with button style, like

demo

 Menu {
      Button("Today") {}
      Button("Tomorrow") {}
 } label: {
      Label("Add Date", systemImage: "calendar")
 }
 .menuStyle(.borderedButton)
Sign up to request clarification or add additional context in comments.

Comments

-1

Placing a Button around the context menu means that the button is managing all the click events, and none of them get through to the contextMenu modifier.

You could move the modifier to attach onto the button itself, and you get something that executes the button action on left click, but displays the context menu when right-clicked:

  Button {
    print("Clicked")
  } label: {
    Label("Add Date", systemImage: "calendar")
  }
  .contextMenu(menuItems)

Context menu displayed on button

2 Comments

Thanks! This work but how can I make it work on Button tap. Your code works when I right click on the Button.
I've not had a need to context menus on left click in macOS so I don't 100% know, I'm afraid! The closest I can find in the docs is to use Menu instead, which produces a drop-down style menu. By default it expands horizontally to fill the whole space, but you could use a frame modifier if needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.