swift - NSStatusBar + swift : title shows and immediately disappear

标签 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"

    }

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

最佳答案

确实你需要对状态项的强引用

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

关于swift - NSStatusBar + swift : title shows and immediately disappear,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44567756/

相关文章:

ios - 我的 iPhone 应用程序无法在 Apple Silicon Mac 上使用

c++ - 如何在批处理模式下工作

macos - Mavericks 和 NSStatusItem 的具有多个监视器的自定义 View

macos - NSClickGestureRecognizer 不适用于 NSStatusItem

swift - 变形 Sprite 直到纹理不再连续 - 如何保持接触检测?

swift - 使用 Swift 3.0 将 CoreData 保存到 Web 服务器

swift - 性能:Array.removeAll 与 `= []`

ios - 如何在 iOS Swift 项目中实现向下箭头/插入符号(如在 iOS 9 音乐应用程序中)?

ios - How to install Xcode in MAC OS running in VMware - Xcode can't be installed on because OS X version 10.12 or later required