If you're looking to build a menu bar app on macOS using Swift, you'll want to familiarize yourself with the AppKit framework. Below is a simple example of how to create a basic menu bar app that displays an icon and a menu.
import Cocoa
@main
class AppDelegate: NSObject, NSApplicationDelegate {
var statusItem: NSStatusItem!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Create the status item and set the icon
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
if let button = statusItem.button {
button.image = NSImage(systemSymbolName: "star", accessibilityDescription: "Star Icon")
button.action = #selector(showMenu)
}
// Create the menu
let menu = NSMenu()
menu.addItem(NSMenuItem(title: "Item 1", action: #selector(menuItemAction), keyEquivalent: "1"))
menu.addItem(NSMenuItem(title: "Item 2", action: #selector(menuItemAction), keyEquivalent: "2"))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit", action: #selector(NSApplication.terminate), keyEquivalent: "q"))
statusItem.menu = menu
}
@objc func showMenu() {
statusItem.menu?.popUp(positioning: nil, at: NSPoint(x: 0, y: 0), in: nil)
}
@objc func menuItemAction(sender: NSMenuItem) {
print("\(sender.title) clicked")
}
}
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?