【问题标题】:Xcode NSStatusBar Item not appearingXcode NSStatusBar 项目未出现
【发布时间】:2019-02-19 18:04:04
【问题描述】:

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

我查看了文档,发现最近发生了一些变化,例如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!"

}

【问题讨论】:

  • 如果你删除let会发生什么?
  • 不起作用 - 说我有一个未解析的标识符...

标签: swift nsstatusitem nsstatusbar


【解决方案1】:

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

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

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

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

【讨论】:

  • 好奇怪的家伙!只需在 appDidFinishLaunching 之外声明 var 就可以了。
【解决方案2】:
  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(_:))
        }
    }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 2014-07-26
    • 2020-09-23
    • 2023-03-10
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    相关资源
    最近更新 更多