2

我正在尝试向状态栏添加一个项目,但是当我启动应用程序时,该项目只出现在左上角一瞬间,然后很快消失。

我浏览了文档,我可以看到最近发生了一些变化,例如statusItem.title变成了statusItem.button?.title. 但似乎没有遗漏任何其他东西。有什么帮助吗?

这是我的代码:

var statusItem : NSStatusItem? = nil

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application

        let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
        statusItem.button?.title = "Connect!"

}
4

2 回答 2

2

啊辉煌。这行得通!谢谢萨利赫。在玩弄了我们的两个代码之后,我的似乎可以使用顶部的 var 声明并且没有 NSMenuDelegate 实例。我的问题似乎是我在说:

让 statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)

我所要做的就是删除“让”,然后说:

statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)

于 2019-02-19T20:11:02.047 回答
1
  1. AppDelegate 应该是NSMenuDelegate的一个实例
  2. 在创建时定义statusItem
  3. 在applicationDidFinishLaunching回调中设置按钮标题

    class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
    let statusItem = NSStatusBar.system.statusItem(withLength:NSStatusItem.variableLength)
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        if let button = statusItem.button {
            //button.image = NSImage(named:NSImage.Name("StatusBarButtonImage"))
            button.title = "connect"
            //button.action = #selector(doSomething(_:))
        }
    }
    
于 2019-02-19T19:04:04.977 回答