I have a SwiftUI based app. For lots of reasons I was forced to use NSDocument instead of using DocumentGroup.
I configure the main menu in my AppDelegate.
It has the following code:
let fileMenuItem = NSMenuItem()
let fileMenu = NSMenu(title: "File")
fileMenu.addItem(withTitle: "New", action: #selector(NSDocumentController.newDocument(_:)), keyEquivalent: "n")
fileMenu.addItem(withTitle: "Open...", action: #selector(NSDocumentController.openDocument(_:)), keyEquivalent: "o")
The New and Open work as expected.
It is my understanding that the NSDocumentController should automatically add the "Open Recent" menu when it sees the Open action based on the NSDocumentController.
It is not appearing.
When I print the state of the recent documents using
print("recent documents \(NSDocumentController.shared.recentDocumentURLs), maximum \(NSDocumentController.shared.maximumRecentDocumentCount)")
I see the recent document urls and a count of 10.
What can I do to make the menu appear?
Thanks for the help.
Your app still uses NSDocumentController
+ NSWindowController
+ NSDocument
, and so AppKit can manage the Open Recent
menu for you. To make it work:
- Set up the menu bar earlier so the menu is there when AppKit checks if it should create the
Open Recent
menu for you . - Make sure you have a menu item connected to
openDocument(_:)
.
The following code snippet should do the trick:
class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
...
/**
Set up the menu bar in applicationWillFinishLaunching so the menu is there when AppKit does the check.
*/
func applicationWillFinishLaunching(_ notification: Notification) {
self.setupMainMenu()
}
func applicationDidFinishLaunching(_ notification: Notification) {
...
}
private func setupMainMenu() {
...
fileMenu.addItem(withTitle: "Open...", action: #selector(NSDocumentController.openDocument(_:)), keyEquivalent: "o”)
...
}
Best,
——
Ziqiao Chen
Worldwide Developer Relations.