我想为 macOS 制作状态栏,但在我运行应用程序后,标题显示并立即消失
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
statusItem.title = "Hello"
}
我认为引用有问题,但不知道如何解决这个问题。
最佳答案
实际上,您需要对状态项进行强引用
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
}()