【问题标题】:How to draw custom view in NSStatusBar?如何在 NSStatusBar 中绘制自定义视图?
【发布时间】:2020-02-03 09:30:30
【问题描述】:

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

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

【问题讨论】:

  • 将视图添加到按钮的子视图中
  • @vadian 正如我所写:“我试图将它作为子视图添加到按钮中,但没有成功。”
  • 原因是别的:与UIView 不同,您必须使用view.wantsLayer = true 启用NSView 中的层。还要考虑自定义视图的高度限制为状态栏的高度。
  • 我已将.wantsLayer = true 添加到视图和按钮中,但仍然没有显示。只是一个空白的可点击方块,但看不到任何颜色。
  • 我还在使用statusBarItem = statusBar.statusItem(withLength: NSStatusItem.squareLength) 来获得固定大小。

标签: swift macos cocoa nsstatusitem nsstatusbar


【解决方案1】:
  • 在类的顶层创建对状态项的强引用

    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)
    
    }
    

【讨论】:

  • 谢谢!有用。我的问题是我在view.layer?.backgroundColor 之后设置了view.wantsLayer = true。它必须先去工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多