12

NSOpenPanel 在“UIKit for Mac”平台上不可用: https ://developer.apple.com/documentation/appkit/nsopenpanel

如果 Apple 不提供内置方式,我猜有人会创建一个基于 SwiftUI 和FileManager的库,显示选择文件的对话框。

4

2 回答 2

15

这是使用 Catalyst 和 UIKit 为 macOS 选择文件的解决方案

在您的 swiftUI 视图中:

Button("Choose file") {
    let picker = DocumentPickerViewController(
        supportedTypes: ["log"], 
        onPick: { url in
            print("url : \(url)")
        }, 
        onDismiss: {
            print("dismiss")
        }
    )
    UIApplication.shared.windows.first?.rootViewController?.present(picker, animated: true)
}

DocumentPickerViewController 类:

class DocumentPickerViewController: UIDocumentPickerViewController {
    private let onDismiss: () -> Void
    private let onPick: (URL) -> ()

    init(supportedTypes: [String], onPick: @escaping (URL) -> Void, onDismiss: @escaping () -> Void) {
        self.onDismiss = onDismiss
        self.onPick = onPick

        super.init(documentTypes: supportedTypes, in: .open)

        allowsMultipleSelection = false
        delegate = self
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension DocumentPickerViewController: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        onPick(urls.first!)
    }

    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        onDismiss()
    }
}
于 2020-02-28T13:13:17.377 回答
8

两者都在 Catalyst 中工作UIDocumentPickerViewControllerUIDocumentBrowserViewController就像在 iOS 上一样使用它们,它们会“神奇地”显示为标准的 Mac 打开/保存对话框。

如果您需要,这里是一个很好的例子:https ://appventure.me/guides/catalyst/how/open_save_export_import.html

于 2019-08-07T16:28:44.347 回答