DEV Community

Khoa Pham
Khoa Pham

Posted on

1 2

How to show context menu from NSButton in macOS

Use NSMenu and popUp

func showQuitMenu() {
    let menu = NSMenu()
    let aboutItem = NSMenuItem(
        title: "About",
        action: #selector(onAboutTouched(_:)),
        keyEquivalent: ""
    )

    let quitItem = NSMenuItem(
        title: "Quit Hacker Pad",
        action: #selector(onQuitTouched(_:)),
        keyEquivalent: ""
    )

    aboutItem.target = self
    quitItem.target = self

    menu.addItem(aboutItem)
    menu.addItem(quitItem)

    menu.popUp(
        positioning: aboutItem,
        at: bottomView.quitButton.frame.origin,
        in: bottomView
    )
}

Use Omnia

let menuHandler = MenuHandler()
menuHandler.add(title: "About", action: {
    NSWorkspace.shared.open(URL(string: "https://onmyway133.github.io/")!)
})

menuHandler.add(title: "Quit Hacker Pad", action: {
    NSApp.terminate(nil)
})

menuHandler.show(from: self.bottomView.gearButton, in: self.bottomView)

Original post https://github.com/onmyway133/blog/issues/435

Sentry blog image

The Visual Studio App Center’s retiring

But sadly….you’re not. See how to make the switch to Sentry for all your crash reporting needs.

Read more

Top comments (1)

Collapse
 
blucreator profile image
BluCreator

Thanks for the snippet! It was very helpful to see it written out so clearly.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs