NSStatusBar + Swift:标题显示并立即消失

时间:2017-06-15 12:38:46

标签: swift macos nsstatusbar

我想要为macOS制作状态栏,但在我运行应用程序标题后显示并立即消失

func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
        statusItem.title = "Hello"

    }

我认为引用有问题,但不知道如何解决这个问题。

1 个答案:

答案 0 :(得分:2)

确实,您需要强烈引用状态项

var statusItem : NSStatusItem!

func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
        statusItem.title = "Hello"

}

但是我建议使用闭包初始化状态项

let statusItem : NSStatusItem = {
    let item =  NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
    item.title = "Hello"
    return item
}()