1

我目前有一个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

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

4

1 回答 1

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

    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)
    
    }
    
于 2020-02-03T09:56:28.487 回答