Skip to content

Instantly share code, notes, and snippets.

@brandonasuncion
Created June 23, 2023 08:22
Show Gist options
  • Select an option

  • Save brandonasuncion/70a6422fb13cab86c78c108cfb4cce3e to your computer and use it in GitHub Desktop.

Select an option

Save brandonasuncion/70a6422fb13cab86c78c108cfb4cce3e to your computer and use it in GitHub Desktop.
easy NSMenu
@resultBuilder
struct MenuItemsBuilder {
static func buildBlock(_ components: NSMenuItem...) -> [NSMenuItem] {
components
}
}
extension NSMenu {
convenience init(title: String? = nil, @MenuItemsBuilder menuItems: () -> [NSMenuItem]) {
self.init()
self.title = title ?? ""
self.items = menuItems()
}
}
extension NSMenuItem {
convenience init(title: String? = nil, @MenuItemsBuilder menuItems: () -> [NSMenuItem]) {
self.init()
self.title = title ?? ""
self.submenu = NSMenu(title: title, menuItems: menuItems)
}
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
let appName = ProcessInfo.processInfo.processName
NSApp.mainMenu = NSMenu {
NSMenuItem {
NSMenuItem(title: "About \(appName)", action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)), keyEquivalent: "")
NSMenuItem.separator()
NSMenuItem(title: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "w")
}
NSMenuItem(title: "View") {
NSMenuItem(title: "Toggle Light/Dark mode", action: #selector(toggleLightDark), keyEquivalent: "t")
NSMenuItem(title: "Copy as Image", action: #selector(screenshot), keyEquivalent: "c")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment