You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS SwiftUI中如何通过fileImporter选择多个文件夹?

iOS SwiftUI 多选文件夹问题解决

你这段代码在macOS能正常多选文件夹,但iOS的fileImporter组件在选择文件夹场景下,即便设置了allowsMultipleSelection: true也不会生效——这是iOS系统层面的限制,SwiftUI封装的这个组件没有开放文件夹多选的权限,其底层依赖的UIDocumentPickerViewController在默认文件夹选择模式下被限制了多选能力。

要在iOS上实现多选文件夹功能,需要直接封装UIKit原生的UIDocumentPickerViewController来突破限制,具体实现如下:

首先创建一个适配SwiftUI的UIKit组件包装器:

import SwiftUI
import UIKit

struct MultiFolderPicker: UIViewControllerRepresentable {
    @Binding var isPresented: Bool
    var onFoldersSelected: ([URL]) -> Void
    
    func makeUIViewController(context: Context) -> UIDocumentPickerViewController {
        let picker = UIDocumentPickerViewController(
            documentTypes: [kUTTypeFolder as String], 
            in: .open
        )
        picker.allowsMultipleSelection = true // 手动开启多选权限
        picker.delegate = context.coordinator
        return picker
    }
    
    func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {}
    
    func makeCoordinator() -> Coordinator {
        Coordinator(parent: self)
    }
    
    class Coordinator: NSObject, UIDocumentPickerDelegate {
        let parent: MultiFolderPicker
        
        init(parent: MultiFolderPicker) {
            self.parent = parent
        }
        
        func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
            parent.onFoldersSelected(urls)
            parent.isPresented = false
        }
        
        func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
            parent.isPresented = false
        }
    }
}

然后在ContentView中替换原有的fileImporter使用这个自定义组件:

struct ContentView: View {
    @State private var isShowingPicker = false
    
    var body: some View {
        Button("Open Folders") {
            isShowingPicker.toggle()
        }
        .sheet(isPresented: $isShowingPicker) {
            MultiFolderPicker(isPresented: $isShowingPicker) { urls in
                for url in urls {
                    print(url.lastPathComponent)
                }
            }
        }
    }
}

核心说明

  • 直接操作UIKit原生的UIDocumentPickerViewController,手动开启allowsMultipleSelection,绕过SwiftUI封装组件的限制
  • 通过UIViewControllerRepresentable协议将UIKit组件转换为SwiftUI可调用的View
  • 借助Coordinator处理选择回调,把选中的文件夹URL传递回SwiftUI视图逻辑中

内容的提问来源于stack exchange,提问作者swiftPunk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 20:34:58