How to add back or cancel button to dismiss UIDocumentBrowser

2.1k Views Asked by At

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

3

There are 3 best solutions below

0
On BEST ANSWER

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.

0
On

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)

  }

}
0
On

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: