UIDocumentPickerViewController在macOS上的SwiftUI中(macCatalyst)

15

所以我一直在试图将一个小的SwiftUI iPad应用程序“移动”到Mac中,但我在UIDocumentPickerViewController方面遇到了一些困难。

我已经像下面这样在UIViewControllerRepresentable中包装了UIDocumentPickerViewController

struct DocumentPickerView: UIViewControllerRepresentable {
  func makeUIViewController(context: Context) -> UIDocumentPickerViewController {
    let documentPicker = UIDocumentPickerViewController(documentTypes: [(kUTTypeImage as String)], in: .import)
    return documentPicker
  }

  func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {

  }
}

并像这样显示:

struct ContentView: View {
@State var shows = false
var body: some View {
    Button(action: { self.shows.toggle() }) {
        Text("Select File")
    }
    .sheet(isPresented: self.$shows) {
        DocumentPickerView()
    }
  }
}

iPad上一切正常, iPad

但是在Mac上,UIDocumentPickerViewController无法显示,我们只能看到这个空白的模态框:

Mac


3
如果我在Catalyst中使用UIKit,它会打开macOS文件选择器。当我使用SwiftUI和Catalyst时,我得到一个空白视图。我希望SwiftUI的行为与此相同。 - ALex Popa
我遇到了同样的问题。这一定是SwiftUI中的一个bug。在macOS上,它应该将UIDocumentPickerViewController真正转换为NSOpenPanel。肯定是个bug! - jogga
太好了!希望他们能尽快修复它。 - ALex Popa
1
如果你正在处理一个基于文档的应用程序,就像我现在所做的一样,你可以通过让UIDocumentBrowserViewController呈现对话框来解决问题。这很繁琐...但至少它能工作 ;-) - jogga
1
let controller = UIDocumentPickerViewController(url: tempURL, in: .moveToService) controller.delegate = self if let presentedViewController = self.presentedViewController { // let the ContentView present the self.modalSelection = .save presentedViewController.present(controller, animated: true) } - jogga
显示剩余6条评论
2个回答

1
我已经替换了过时的方法并启用了提供的主题起始代码所请求的权限,现在它可以正常工作。
已在Xcode 13.3 / macOS 12.2上进行了测试。
import UniformTypeIdentifiers
struct DocumentPickerView: UIViewControllerRepresentable {
  func makeUIViewController(context: Context) -> UIDocumentPickerViewController {
    let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.image], asCopy: true)
    return documentPicker
  }

  func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {

  }
}

配置

并演示如何打开标准的 macOS 选择器

输入图像描述


0
由于某种原因(我不知道更具体的细节),以下方法对我有用(针对Catalyst):
不要使用in: .import
let documentPicker = UIDocumentPickerViewController(
    documentTypes: [(kUTTypeImage as String)], 
    in: .import
)

使用 in: .open

let documentPicker = UIDocumentPickerViewController(
    documentTypes: [(kUTTypeImage as String)], 
    in: .open
)

我还没有检查过这个功能在iOS上是否被维护,但也许你可以使用某种“标志”来确定是使用.import还是.open


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接