在 macOS Big Sur 中,UIDocument.open()
自动将打开的文件添加到“打开最近使用的文件”菜单中。但是,菜单项没有文件图标(AppKit 中有!)。
你可以查看苹果的示例构建基于文档浏览器的应用程序 https://developer.apple.com/documentation/uikit/view_controllers/building_a_document_browser-based_app举个例子,使用UIDocumentBrowserViewController
and UIDocument
.
获取真实的东西要复杂得多,并且涉及到调用 Objective-C 方法。我知道有两种方法来填充“打开最近的”菜单 - 手动使用 UIKit+AppKit,或使用私有 AppKit API“自动”。后者应该也可以在 Mac Catalyst 的早期版本(Big Sur 之前)中工作,但在 UIKit 中存在更多错误。
由于您无法直接在 Mac Catalyst 应用程序中使用 AppKit,因此有两种选择:
- 创建一个使用 Swift 或 Objective-C 桥接到 AppKit 的应用程序包,并从应用程序加载该包。
- 使用字符串从基于 UIKit 的应用程序调用 AppKit API。我正在使用Dynamic https://github.com/mhdhejazi/Dynamic包为此。
手动填充“打开最近使用的内容”菜单
下面显示的示例是从 Mac Catalyst 调用 AppKit。
class AppDelegate: UIResponder, UIApplicationDelegate {
override func buildMenu(with builder: UIMenuBuilder) {
guard builder.system == .main else { return }
var recentFiles: [UICommand] = []
if let recentFileURLs = ObjC.NSDocumentController.sharedDocumentController.recentDocumentURLs.asArray {
for i in 0..<(recentFileURLs.count) {
guard let recentURL = recentFileURLs.object(at: i) as? NSURL else { continue }
guard let nsImage = ObjC.NSWorkspace.sharedWorkspace.iconForFile(recentURL.path).asObject else { continue }
guard let imageData = ObjC(nsImage).TIFFRepresentation.asObject as? Data else { continue }
let image = UIImage(data: imageData)?.resized(fittingHeight: 16)
guard let basename = recentURL.lastPathComponent else { continue }
let item = UICommand(title: basename,
image: image,
action: #selector(openDocument(_:)),
propertyList: recentURL.absoluteString)
recentFiles.append(item)
}
}
let clearRecents = UICommand(title: "Clear Menu", action: #selector(clearRecents(_:)))
if recentFiles.isEmpty {
clearRecents.attributes = [.disabled]
}
let clearRecentsMenu = UIMenu(title: "", options: .displayInline, children: [clearRecents])
let recentMenu = UIMenu(title: "Open Recent",
identifier: nil,
options: [],
children: recentFiles + [clearRecentsMenu])
builder.remove(menu: .openRecent)
let open = UIKeyCommand(title: "Open...",
action: #selector(openDocument(_:)),
input: "O",
modifierFlags: .command)
let openMenu = UIMenu(title: "",
identifier: nil,
options: .displayInline,
children: [open, recentMenu])
builder.insertSibling(openMenu, afterMenu: .newScene)
}
@objc func openDocument(_ sender: Any) {
guard let command = sender as? UICommand else { return }
guard let urlString = command.propertyList as? String else { return }
guard let url = URL(string: urlString) else { return }
NSLog("Open document \(url)")
}
@objc func clearRecents(_ sender: Any) {
ObjC.NSDocumentController.sharedDocumentController.clearRecentDocuments(self)
UIMenuSystem.main.setNeedsRebuild()
}
菜单不会自动刷新。您必须通过调用来触发重建UIMenuSystem.main.setNeedsRebuild()
。每当您打开文档时都必须执行此操作,例如在提供给的块中UIDocument.open()
,或保存文档。下面是一个例子:
class MyViewController: UIViewController {
var document: UIDocument? // set by the parent view controller
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Access the document
document?.open(completionHandler: { (success) in
if success {
// Display the document
} else {
// Report error
}
// 500 ms is probably too long
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
UIMenuSystem.main.setNeedsRebuild()
}
})
}
}
自动填充菜单 (AppKit)
以下示例使用:
-
NSMenu
的私有API_setMenuName:
设置菜单名称以使其本地化,以及
-
NSDocumentController
's _installOpenRecentMenus
安装“打开最近使用的”菜单。
- (void)setupRecentMenu {
NSMenuItem *clearMenuItem = [self _findMenuItemWithName:@"Open Recent" in:NSApp.mainMenu.itemArray];
if (!clearMenuItem) {
NSLog(@"Warning: 'Open Recent' menu not found");
return;
}
NSMenu *openRecentMenu = [[NSMenu alloc] initWithTitle:@"Open Recent"];
[openRecentMenu performSelector:NSSelectorFromString(@"_setMenuName:") withObject:@"NSRecentDocumentsMenu"];
clearMenuItem.submenu = openRecentMenu;
[NSDocumentController.sharedDocumentController valueForKey:@"_installOpenRecentMenus"];
}
- (NSMenuItem * _Nullable)_findMenuItemWithName:(NSString * _Nonnull)name in:(NSArray<NSMenuItem *> * _Nonnull)array {
for (NSMenuItem *item in array) {
if ([item.title isEqualToString:name]) {
return item;
}
if (item.hasSubmenu) {
NSMenuItem *subitem = [self _findMenuItemWithName:name in:item.submenu.itemArray];
if (subitem) {
return subitem;
}
}
}
return nil;
}
在你的buildMenu(with:)
method:
class AppDelegate: UIResponder, UIApplicationDelegate {
override func buildMenu(with builder: UIMenuBuilder) {
guard builder.system == .main else { return }
let open = UIKeyCommand(title: "Open...",
action: #selector(openDocument(_:)),
input: "O",
modifierFlags: .command)
let recentMenu = UIMenu(title: "Open Recent",
identifier: nil,
options: [],
children: [])
let openMenu = UIMenu(title: "",
identifier: nil,
options: .displayInline,
children: [open, recentMenu])
builder.remove(menu: .openRecent)
builder.insertSibling(openMenu, afterMenu: .newScene)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
self?.myObjcBridge?.setupRecentMenu()
}
}
但是,我发现这种方法存在一些问题。图标似乎已关闭(它们更大),并且“清除菜单”命令在第一次使用后并未禁用。重建菜单可以解决该问题。
2020 年 12 月 30 日更新
macCatalyst 14 (Big Sur) 确实安装了“打开最近使用的”菜单,但该菜单没有图标。
使用 Dynamic 包的速度明显慢。我按照 Peter Steinberg 的演讲在 Objective-C 中实现了相同的逻辑。虽然这有效,但我注意到图标太大,而且我找不到解决这个问题的方法。
此外,使用 AppKit 的私有 API,“打开最近的”字符串不会自动本地化(但“清除菜单”会自动本地化!)。
我目前的做法是:
- 使用应用程序包(在 Objective-C 中)
a) 用途
NSDocumentController
查询最近的文件。
b) 用途NSWorkspace
获取文件的图标。
- The
buildMenu
方法调用包,获取文件/图标并手动创建菜单项。
- 应用程序包加载
NSImageNameMenuOnStateTemplate
系统映像并将此大小提供给 mac Catalyst 应用程序,以便它可以调整图标大小。
请注意,我还没有实现安全书签的逻辑(对此不熟悉,需要进一步调查)。彼得谈到了这一点。
显然,我需要自己提供字符串的翻译。但没关系。
以下是应用程序包中的相关代码:
@interface RecentFile: NSObject<RecentFile>
- (instancetype)initWithURL: (NSURL * _Nonnull)url icon:(NSImage *)image;
@end
@implementation AppKitBridge
@synthesize recentFiles;
@synthesize menuIconSize;
@end
- (instancetype)init {
// ...
NSImage *templateImage = [NSImage imageNamed:NSImageNameMenuOnStateTemplate];
self->menuIconSize = templateImage.size;
}
- (NSArray<NSObject<RecentFile> *> *)recentFiles {
NSArray<NSURL *> *recents = [[NSDocumentController sharedDocumentController] recentDocumentURLs];
NSMutableArray<SGRecentFile *> *result = [[NSMutableArray alloc] init];
for (NSURL *url in recents) {
if (!url.isFileURL) {
NSLog(@"Warning: url '%@' is not a file URL", url);
continue;
}
NSImage *icon = [[NSWorkspace sharedWorkspace] iconForFile:[url path]];
RecentFile *f = [[RecentFile alloc] initWithURL:url icon:icon];
[result addObject:f];
}
return result;
}
- (void)clearRecentFiles {
[NSDocumentController.sharedDocumentController clearRecentDocuments:self];
}
然后填充UIMenu
来自 macCatalyst 代码:
@available(macCatalyst 13.0, *)
func createRecentsMenuCatalyst(openDocumentAction: Selector, clearRecentsAction: Selector) -> UIMenuElement {
var commands: [UICommand] = []
if let recentFiles = appKitBridge?.recentFiles {
for rf in recentFiles {
var image: UIImage? = nil
if let cgImage = rf.image {
image = UIImage(cgImage: cgImage).scaled(toHeight: menuIconSize.height)
}
let cmd = UICommand(title: rf.url.lastPathComponent,
image: image,
action: openDocumentAction,
propertyList: rf.url.absoluteString)
commands.append(cmd)
}
}
let clearRecents = UICommand(title: "Clear Menu", action: clearRecentsAction)
if commands.isEmpty {
clearRecents.attributes = [.disabled]
}
let clearRecentsMenu = UIMenu(title: "", options: .displayInline, children: [clearRecents])
let menu = UIMenu(title: "Open Recent",
identifier: UIMenu.Identifier("open-recent"),
options: [],
children: commands + [clearRecentsMenu])
return menu
}
Sources
- 彼得·斯坦伯格的演讲发布 Mac Catalyst 应用程序:好的、坏的和丑陋的 https://youtu.be/EK0O8_Tt6TE?t=1181
- Appe's 使用菜单元素访问操作 https://developer.apple.com/tutorials/mac-catalyst/accessing-actions-using-menu-elements
- 东东公司AppKitified GitHub 存储库 https://github.com/stuffmc/AppKitified显示如何创建和加载包。