How do I add context menus and previews on macOS using Swift?

In this guide, you will learn how to add context menus and previews on macOS using Swift. This functionality allows users to interact with macOS applications more effectively by providing additional options via right-click or touchpad gestures.

Example Code

import Cocoa class ViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Enable the context menu let menu = NSMenu() menu.addItem(NSMenuItem(title: "Option 1", action: #selector(option1Selected), keyEquivalent: "")) menu.addItem(NSMenuItem(title: "Option 2", action: #selector(option2Selected), keyEquivalent: "")) self.view.menu = menu } @objc func option1Selected() { print("Option 1 selected") } @objc func option2Selected() { print("Option 2 selected") } override func mouseDown(with event: NSEvent) { if event.type == .rightMouseDown { NSMenu.popUpContextMenu(self.view.menu!, with: event, for: self.view) } } }

context menus macOS Swift application development user interface