Swift 如何从其他文件更新NSStatusItem?

Swift 如何从其他文件更新NSStatusItem?,swift,macos,nsstatusitem,nsstatusbar,Swift,Macos,Nsstatusitem,Nsstatusbar,当用户在“我的设置”视图中单击按钮时,我想更新状态栏中NSStatusItem的button.title属性。但是,NSStatusItem当前没有更改 AppDelegate: let statusItem = NSStatusBar.system.statusItem(withLength:NSStatusItem.variableLength) func applicationDidFinishLaunching(_ aNotification: Notification) {

当用户在“我的设置”视图中单击按钮时,我想更新状态栏中NSStatusItem的button.title属性。但是,NSStatusItem当前没有更改

AppDelegate:

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

func applicationDidFinishLaunching(_ aNotification: Notification) {
    statusItem.button?.title = "A title"
}

func updateTitle(newTitle : String) {
    statusItem.button?.title = newTitle
}
设置可视控制器:

@IBAction func didKlickChange(_ sender: Any) {
    AppDelegate().updateTitle(newTitle: "Updated title")
}
当我运行应用程序时,状态栏会显示一个标题为“a title”的新状态项。很好,到目前为止。 但是当我点击按钮时,唯一发生的事情是一个新的状态项在很短的时间内出现在旧的状态项旁边。旧版本不会得到更新。 有没有合适的解决办法

谢谢你的帮助

AppDelegate()
创建一个全新的类实例,该实例不是您期望的实例。你需要实际的参考资料

@IBAction func didKlickChange(_ sender: Any) {
    (NSApp.delegate as! AppDelegate).updateTitle(newTitle: "Updated title")
}
可能的副本。