如何在平台"Mac版UIKit"上使用SwiftUI打开文件对话框? [英] How to open file dialog with SwiftUI on platform "UIKit for Mac"?

查看:94
本文介绍了如何在平台"Mac版UIKit"上使用SwiftUI打开文件对话框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

NSOpenPanel is not available on platform "UIKit for Mac": https://developer.apple.com/documentation/appkit/nsopenpanel

如果Apple不提供内置方式,我想有人会基于SwiftUI和

If Apple doesn't provide a built-in way, I guess someone will create a library based on SwiftUI and FileManager that shows the dialog to select files.

推荐答案

以下是使用Catalyst& for Mac为macOS选择文件的解决方案.UIKit

Here's a solution to select a file for macOS with Catalyst & UIKit

在您的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()
    }
}

这篇关于如何在平台"Mac版UIKit"上使用SwiftUI打开文件对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆