iOS中如何禁用UIDocumentPickerViewController的文件编辑功能?
如何禁用UIDocumentPickerViewController的文件/文件夹编辑操作
嘿,我完全懂你的困扰——UIDocumentPickerViewController确实没有类似allowsEditing的直接属性来禁用重命名、分享这些编辑操作,但咱们有两种靠谱的解决方案:
方案一:切换到.open模式(最简单最优解)
如果你的业务逻辑允许直接读取文件而不需要复制到App沙盒,那直接把文档选择器的模式从.import改成.open就完事了。.open模式默认就不会显示任何编辑操作(重命名、复制、分享都没了),完全符合你的需求。
修改后的代码:
func documentPicker(from view: UIView) { // 将.in: .import替换为.in: .open let importMenu = UIDocumentPickerViewController(documentTypes: [String(kUTTypePDF), String(kUTTypeJPEG), String(kUTTypeGIF)], in: .open) importMenu.delegate = self importMenu.modalPresentationStyle = .popover if let presentation = importMenu.popoverPresentationController { presentation.permittedArrowDirections = .any presentation.sourceView = view presentation.sourceRect = view.bounds } parentController?.present(importMenu, animated: true, completion: nil) }
注意:使用
.open模式需要确保你的App已经配置了相应的文件访问权限(比如iCloud权限或者本地文件访问权限),否则可能无法正常访问文件。
方案二:针对.import模式的自定义处理(必须保留导入功能时)
如果业务上必须用.import模式(比如需要把文件复制到App沙盒),那我们需要手动处理两个点:隐藏导航栏的编辑按钮,以及禁用文件列表的长按上下文菜单。
步骤1:子类化UIDocumentPickerViewController
创建一个自定义的只读版本文档选择器,重写相关方法来禁用编辑功能:
class ReadOnlyDocumentPicker: UIDocumentPickerViewController { override func viewDidLoad() { super.viewDidLoad() // 递归查找文件列表的TableView,禁用上下文菜单 if let tableView = findTableView(in: view) { tableView.showsContextMenu = false } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // 隐藏导航栏右侧的编辑按钮 navigationItem.rightBarButtonItem?.isHidden = true } // iOS 13+ 额外拦截上下文菜单的生成 override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { return nil } // 递归查找子视图中的UITableView private func findTableView(in view: UIView) -> UITableView? { if let tableView = view as? UITableView { return tableView } for subview in view.subviews { if let tableView = findTableView(in: subview) { return tableView } } return nil } }
步骤2:替换原有的文档选择器实例
把你原代码中的UIDocumentPickerViewController换成我们自定义的ReadOnlyDocumentPicker:
func documentPicker(from view: UIView) { // 使用自定义的只读文档选择器 let importMenu = ReadOnlyDocumentPicker(documentTypes: [String(kUTTypePDF), String(kUTTypeJPEG), String(kUTTypeGIF)], in: .import) importMenu.delegate = self importMenu.modalPresentationStyle = .popover if let presentation = importMenu.popoverPresentationController { presentation.permittedArrowDirections = .any presentation.sourceView = view presentation.sourceRect = view.bounds } parentController?.present(importMenu, animated: true, completion: nil) }
这样处理后,无论是导航栏的编辑按钮,还是长按文件弹出的重命名、分享菜单,都会被完全禁用,用户只能选择文件进行导入操作。
内容的提问来源于stack exchange,提问作者ritika gupta




