如何使用 Mac-Catalyst 添加最近的文件

2023-12-20

在默认的“文件”菜单中,它有“打开最近的>”菜单项,并且它是自动添加的。 目前,如果用户从 Finder 打开关联文件,则会自动添加最近的项目(在 Big Sur 上)。但是如果用户使用 UIDocumentPickerViewController 从我的应用程序打开,它不会添加最近的菜单项。

我想在“打开最近的>”下添加此菜单项,并从我的代码中清除项目。 有帮助文档或者示例代码吗? 谢谢。


在 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,因此有两种选择:

  1. 创建一个使用 Swift 或 Objective-C 桥接到 AppKit 的应用程序包,并从应用程序加载该包。
  2. 使用字符串从基于 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)

以下示例使用:

  1. NSMenu的私有API_setMenuName:设置菜单名称以使其本地化,以及
  2. 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,“打开最近的”字符串不会自动本地化(但“清除菜单”会自动本地化!)。

我目前的做法是:

  1. 使用应用程序包(在 Objective-C 中) a) 用途NSDocumentController查询最近的文件。 b) 用途NSWorkspace获取文件的图标。
  2. The buildMenu方法调用包,获取文件/图标并手动创建菜单项。
  3. 应用程序包加载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显示如何创建和加载包。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Mac-Catalyst 添加最近的文件 的相关文章

  • 如何右对齐 UILabel?

    Remark 实施 myLabel textAlignment right does not解决了我的问题 这不是我所要求的 我想要实现的是让标签对齐右对齐 为了更清楚地说明 这就是如何left对齐外观 就是这样justify对齐外观 if
  • 将自定义图像设置为 UIBarButtonItem 但它不显示任何图像

    我想将自定义图像设置为 UIBarButtonItem 但它只显示周围的矩形框并且不显示实际图像 func setupBrowserToolbar let browser UIToolbar frame CGRect x 0 y 20 wi
  • Swift 3 中的 JSON 解析

    有没有人能够找到一种在 Swift 3 中解析 JSON 文件的方法 我已经能够返回数据 但在将数据分解为特定字段时我没有成功 我会发布示例代码 但我已经尝试了很多不同的方法但没有成功 并且没有保存任何代码 我想要解析的基本格式是这样的 提
  • Swift 中的柯里函数

    我想创建一个返回柯里函数的函数 如下所示 func addTwoNumbers a Int b Int gt Int return a b addTwoNumbers 4 b 6 Result 10 var add4 addTwoNumbe
  • iOS 防止计时器 UILabel 在数字变化时“晃动”

    我有一个UILabel它以以下格式显示计时器的输出MM ss SS 分 秒 厘秒 但是随着厘秒宽度的变化 它从左向右 摇动 例如 11 比 33 窄 有什么办法可以减轻这种情况吗 我尝试过将其居中 给它固定的宽度 但它们似乎没有帮助 从iO
  • AWS S3 公共对象与私有对象?

    回到 S3 我的存储桶中有图像的 URL 我将在我的应用程序中呈现这些图像 但它们被设置为私有 当我尝试单击该链接时 它显示 访问被拒绝 当我将链接的设置更改为公共时 它会通过 但是我读到公共访问并不是最安全的事情 所以这本质上是一个由两部
  • ios - Gamekit 的 GKOctree 未找到元素

    我正在尝试使用GKOctree https developer apple com documentation gameplaykit gkoctree用于高效检索 3D 空间中的对象 然而 以下代码似乎没有按预期工作 import Gam
  • 当 UITextField 已满或空时显示警报 Swift

    下面的代码中 如果 userNameTF 或 passwordTF 已满或为空 则会显示警报 IBAction func LoginBtn sender AnyObject let userName userNameTF text let
  • 如何在 Swift 中获取字典中最后输入的值?

    如何获取 Swift 字典中最后输入的值 例如 我如何从下面获取值 CCC var dictionary Dictionary
  • NVActivityIndi​​catorView 仅适用于特定视图

    我正在使用这个库https github com ninjaprox NVActivityIndi catorView https github com ninjaprox NVActivityIndicatorView用于显示加载指示器
  • SKNode 上的 runAction 未完成

    我使用 NSOperation 子类来获取串行执行SKAction正如这个问题中所描述的 如何在 Swift 中子类化 NSOperation 以将 SKAction 对象排队以进行串行执行 https stackoverflow com
  • Swift C 回调 - Swift 类指针的 takeUnretainedValue 或 takeRetainedValue

    我有一些UIView or UITableViewCell 里面我有 C 回调 例如 CCallback bridge self observer data gt Void in let mySelf Unmanaged
  • CGPoint 标量乘法 Swift

    我正在 SpriteKit 中构建一个平台游戏 并将为我的实体实现更新功能 以便它们根据重力和速度移动 但是 我需要使添加的速度量与增量时间成比例 以防止帧速率影响我的实体的移动方式 因此我将导入 GLKit 以便我可以使用标量函数 但是
  • 使用 UISearchBar 过滤数组

    我目前正在使用以下代码来过滤数组并将结果显示在我的 tableView 中 问题是 只有当搜索与确切的单词匹配时 才会返回结果 如何更改数组过滤器以在输入时搜索每个字符 let data Mango Grape Berry Orange A
  • 列表不符合 Encodable

    因此 我正在使用领域 并且两个模型之间有以下关系 A unit has many tests Unit model class Unit Object Decodable objc dynamic var id String let tes
  • Transit MKDirectionsRequest 产生 null 错误 Error Domain=MKErrorDomain Code=5 "(null)"

    我正在尝试使用 MapKit Directions Request 来获取两个坐标之间的交通方向 当我切换到其他 非 Transit 类型时 下面的代码可以工作 但是当我切换到 Transit 时 它会抛出一个错误 该错误在 Apple 文
  • Swift 中带圆角的 NSWindow

    我想要一个圆角的窗户 但我在每个角落都有一个白点 Code let effect NSVisualEffectView frame NSRect x 0 y 0 width 0 height 0 effect blendingMode be
  • UISearchController 保留问题

    我正在尝试使用 UISearchController 但是我遇到了无法解决的保留问题 MainTableview 有两个部分 第1节 基于某些正则表达式过滤数据 第2节 All Data 我将 UISearchController 添加到我
  • 按范围迭代数组

    我有一个数组 1 2 3 4 5 6 100 我希望将此数组迭代 5 次 具体来说 取数组的前 5 个数字并获取平均值 继续处理接下来的 5 个数字并获取平均值 依此类推 我尝试过多种方法 例如Dequeue和 for 循环但未能获得所需的
  • NSPredicate 的 onFormat 字符串

    我想用 id 键对数据进行排序 我如何理解格式字符串的用途NSPredicate格式 我有一个100号的帖子 我的代码 let objectIDs posts map 0 id let predicate NSPredicate forma

随机推荐