如何在 NSStatusBar 中绘制自定义视图?

eiv*_*dml 1 macos cocoa nsstatusitem nsstatusbar swift

我目前有一个带有显示标题的NSStatusBara 。NSStatusBarItem但我不想用自定义替换标题/文本NSView。我怎样才能做到这一点?

我目前有:

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

假设我不想用以下内容替换标题:

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

我怎样才能做到这一点?我尝试将其作为子视图添加到按钮中,但没有成功。

vad*_*ian 6

  • 在类的顶层创建对状态项的强引用

    let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
    
    Run Code Online (Sandbox Code Playgroud)
  • applicationDidFinishLaunching启用图层并将视图添加到按钮的子视图中

    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)
    
    }
    
    Run Code Online (Sandbox Code Playgroud)