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.
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)
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?