macosnsmenunsstatusbar

How to add a button to a NSMenu that is used as Status bar menu?


I am using following code to create a statusbar menu for my app on MacOS:

let statusBarItem = NSStatusBar.system.statusItem(withLength: -1)

 func applicationDidFinishLaunching(_ aNotification: Notification) {

        let menu: NSMenu = NSMenu()
        var menuItem = NSMenuItem()
        menuItem.title = "Hello"
        menu.addItem(menuItem)
      
        statusBarItem.menu=menu
}

This works, but I am wondering how to add custom lines to this menu, e.g. containing a checkbox or a button. See the attached screenshot from VLC video player.

enter image description here


Solution

  • It is quite easy: NSMenuItem has a property view. You can set any view to this.

      let menu: NSMenu = NSMenu()
            var menuItem = NSMenuItem()
            
            let frame = CGRect(origin: .zero, size: CGSize(width: 100, height: 20))
            let viewHint = NSView(frame: frame)
            let switchButton = NSSwitch(frame: frame)
            viewHint.addSubview(switchButton)
            
            
            menuItem.view = viewHint