Reputation: 2120
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?
Upvotes: 2
Views: 2212
Reputation: 96
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:
Upvotes: 0
Reputation: 506
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:
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.
Upvotes: 5
Reputation: 592
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)
}
}
Upvotes: 4