How to draw two lines of text in a NSView subclass ? (macOS system tray)

184 Views Asked by At

I'm trying to write two lines of text in the macOS system tray, very much like iStat pro does for the network activity:

enter image description here

I know I have to subclass NSView to do so, but I can't manage to get it working even for one line:

class CustomView:NSView {

  override func draw(_ dirtyRect: NSRect) {
        let text: NSString = "my string"

        let textRect: NSRect = NSMakeRect(0, 0, 100, 20)
        text.draw(in: textRect)

  }
}

and then:

let statusBar = NSStatusBar.system
statusItem = statusBar.statusItem(withLength: 100)
let view = CustomView()
view.wantsLayer = true
statusItem.button?.addSubview(view)

I've found other threads on stackoverflow:

1

There are 1 best solutions below

1
apodidae On BEST ANSWER

Doubt that it's what you are looking for, but this will put two lines of text in a status item:

import Cocoa

let app = NSApplication.shared
let statusItem = NSStatusBar.system.statusItem(withLength:-1)
statusItem.button?.font = NSFont(name:"Menlo Bold", size: 10.0)
statusItem.button!.title = "one\ntwo"
app.run()

It's still just one button and I don't see how you will separate the selection of each item. Perhaps a drop down menu would work better?