如何添加返回或取消按钮以关闭 UIDocumentBrowser

How to add back or cancel button to dismiss UIDocumentBrowser

我需要出示用于上传文档的 UIDocumentBrowser。但我无法在导航栏中放置后退或取消按钮。下图是 WhatsApp 中文件浏览器的截图。 有人可以帮助我吗?

为 UINavigationBar 和 UIBarButtonItem 使用黑色外观的 CustomDocumentPickerViewController。使用下面的代码

import UIKit

class CustomDocumentPickerViewController: UIDocumentPickerViewController {

  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    UINavigationBar.appearance().tintColor = UIColor.black
    UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.black], for: .normal)
  }

  override func viewWillDisappear(_ animated: Bool) {

    UINavigationBar.appearance().tintColor = UIColor.white // your color
    UIBarButtonItem.appearance().setTitleTextAttributes(nil, for: .normal)
    super.viewWillDisappear(animated)

  }

}

UIDocumentBrowserViewController 设计为仅用作根视图控制器,这就是它没有 "Back" 或 "Cancel" 按钮的原因。根据文档:

https://developer.apple.com/documentation/uikit/view_controllers/adding_a_document_browser_to_your_app

Important

Always assign the document browser as your app's root view controller. Don't place the document browser in a navigation controller, tab bar, or split view, and don't present the document browser modally.

If you want to present a document browser from another location in your view hierarchy, use a UIDocumentPickerViewController instead.