eivindml
eivindml

Reputation: 2530

How to draw custom view in NSStatusBar?

I currently have a NSStatusBar with a NSStatusBarItem with a title displaying. But I wan't to replace the title/text with a custom NSView. How can I do that?

I currently have:

func applicationDidFinishLaunching(_ aNotification: Notification) {
    let statusBar = NSStatusBar.system
    statusBarItem = statusBar.statusItem(withLength: NSStatusItem.variableLength)
    statusBarItem.button?.title = "My Menu Bar App"
}

Let's say I wan't to replace the title with the following:

let view = NSView(frame: NSRect(x: 0, y: 0, width: 40, height: 40))
view.layer?.backgroundColor = NSColor.yellow.cgColor

How can I achieve that? I tried to add it as a subview to the button, with no luck.

Upvotes: 2

Views: 1570

Answers (1)

vadian
vadian

Reputation: 285180

  • Create a strong reference to the status item on the top level of the class

    let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
    
  • in applicationDidFinishLaunching enable the layer and add the view to the subviews of the button

    func applicationDidFinishLaunching(_ aNotification: Notification) {
    
        let view = NSView(frame: NSRect(x: 0, y: 0, width: 22, height: 22))
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.yellow.cgColor
        statusItem.button?.addSubview(view)
    
    }
    

Upvotes: 7

Related Questions