2

I need to present UIDocumentBrowser for uploading a document. But I am not able to place a back or cancel button in the navigation bar. The image below is a screenshot of the file browser in WhatsApp. Can anybody help me?

enter image description here

Do2
  • 1,751
  • 1
  • 16
  • 28
Britto Thomas
  • 2,092
  • 1
  • 15
  • 28

3 Answers3

4

Use CustomDocumentPickerViewController with black appearance for UINavigationBar and UIBarButtonItem. Use the below Code

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)

  }

}
Vicky_Vignesh
  • 584
  • 2
  • 14
4

The UIDocumentBrowserViewController is designed to only be used as a root view controller, which is why it has no "Back" or "Cancel" button. As per the documentation:

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.

Kenster999
  • 466
  • 2
  • 13
0

A great solution for this is to add a custom button through the additionalTrailingNavigationBarButtonItems or additionalLeadingNavigationBarButtonItems property. Example below:

let documentBrowser = UIDocumentBrowserViewController(forOpening: [.jpeg, .png])
let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(didTapDocumentBrowserCancel))
documentBrowser.additionalTrailingNavigationBarButtonItems = [cancelButton]

Then create a function to close the document browser.

@objc private func didTapDocumentBrowserCancel() {
    dismiss(animated: true)
}

References: