工具栏、触控栏和菜单无法识别从 AppDelegate 启动 window

Launching a window from AppDelegate is not recognised by toolbar, Touch Bar and menus

我正在尝试以编程方式从 AppDelegate 启动 window,特别是从 Services Provider 启动它,但效果不是很好,因为工具栏不工作,Touch Bar 不显示,自定义菜单我添加的项目被禁用。 Apple 提供的默认菜单和菜单项有效。

我所有的观点都是在故事板上创建的。默认的 main window 不是从 AppDelegate 启动的。

我这样启动 window。

guard let windowController = NSStoryboard.main?.instantiateController(withIdentifier: .windowController) as? WindowController else { return }

windowController.window?.title = data.title
windowController.viewController?.property = data
windowController.showWindow(self)

但是,如果我通过 segue 启动,它会完美运行。

guard let splitViewController = NSApp.mainWindow?.contentViewController as? NSSplitViewController,
      let viewController = splitViewController.splitViewItems[1].viewController as? ViewController else { return }

viewController.anotherViewController.performSegue(withIdentifier: .segue, sender: data)

那么,我为什么不这样做呢?因为它从主 window 运行,然后程序启动 window 阻止该代码再次运行。仅在只有一个 window.

时有效

我希望它每次都能正常工作。主 window 是关键 window 还是随后的其他非主 windows.

并不重要

如何确保我可以启动一个 window 并且工具栏、触控栏和自定义菜单项也能识别它,如果只有主 window 或其他 windows,它们不是主要的 window,而是不同类型的 windows。

我误解了mainWindow 属性,以为它指的是实际的主要window,而实际上它指向的是重点window。所以,我真正想要的主要 window 是 windows 数组中的第一个 window。

guard let mainWindowController = NSApp.windows.first?.windowController as? MainWindowController,
      let splitViewController = mainWindowController.contentViewController as? SplitViewController,
      let viewController = splitViewController.splitViewItems[1].viewController as? ViewController else { return }

viewController.anotherViewController.performSegue(withIdentifier: .segueIdentifier, sender: data)

菜单项、工具栏和触控栏正常工作并响应用户交互。