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

}

关于swift - 如何在NSStatusBar中绘制自定义 View ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60036391/

10-12 14:42