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



我目前有一个NSStatusBar,带有一个显示标题的NSStatusBarItem。但我不想用自定义NSView替换标题/文本.我该怎么做?

我目前有:

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

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

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

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

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

    let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
    
  • 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)
    }
    

相关内容

  • 没有找到相关文章

最新更新