简体   繁体   中英

How to present a view controller from a detached view controller?

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?

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)

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM