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

👋 While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (1)

Collapse
 
blucreator profile image
BluCreator •

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay