Reputation: 2964
I'm trying to present a view controller modally and get the famous Presenting view controllers on detached view controllers is discouraged
error. I researched it and the consensus solution appears to be making the presentation from the parent, which I tried but did not have success with. I suspect the problem is because the navigation controller was instantiated from a struct as a static property (to make it easier for other view controller's to pop to root as this is what the UX called for).
struct SectionNavigationControllers {
static var one = SectionNavigationController()
static var two = SectionNavigationController()
static var three = SectionNavigationController()
static var four = SectionNavigationController()
}
And here is where one of the navigation controllers is created (using this struct):
let SectionOneRoot = MasterSearchViewController()
func addNavigationController() {
self.addChildViewController(SectionOneRoot)
SectionOneRoot.didMove(toParentViewController: self)
SectionNavigationControllers.one = SectionNavigationController(rootViewController: SectionOneRoot)
view.addSubview(SectionNavigationControllers.one.view)
}
And so when I try to present a view controller modally from MasterSearchViewController
(the root view controller), I get the said error.
navigationController?.present(Random200ViewController(), animated: true, completion: nil)
Ideas?
Upvotes: 2
Views: 1174
Reputation: 3806
Here's a convenience function you can add to any piece of code to present a view controller from anywhere in your app:
func showModally(_ viewController: UIViewController) {
let window = UIApplication.shared.keyWindow
let rootViewController = window?.rootViewController
rootViewController?.present(viewController, animated: true, completion: nil)
}
I hope it helps!
Upvotes: 2
Reputation: 2475
If you want to present it on your app's root viewController, you can do it like this:
let rootVC = UIApplication.shared.keyWindow?.rootViewController
rootVC?.present(Random200ViewController(), animated: true, completion: nil)
Upvotes: 1