Mary Doe
Mary Doe

Reputation: 1323

ContextMenu in macOS App SwiftUI on Button Tap

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

Upvotes: 2

Views: 2379

Answers (2)

Asperi
Asperi

Reputation: 258443

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)

Upvotes: 4

ScottM
ScottM

Reputation: 10502

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

Upvotes: -1

Related Questions