Home > Software engineering >  ContextMenu in macOS App SwiftUI on Button Tap
ContextMenu in macOS App SwiftUI on Button Tap

Time:11-26

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

CodePudding user response:

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

CodePudding user response:

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)
  • Related