Charlie Fish
Charlie Fish

Reputation: 20576

Swift Present View Controller From Another View Controller

I currently have the following function inside of my main view controller (View Controller A).

func myAction() {       
    let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
    let viewControllerC : UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "ViewControllerC") as UIViewController

    self.present(viewControllerC, animated: false, completion: nil)
}

When View Controller A is currently displayed and myAction is called it works fine and displays viewControllerC.

But this function myAction can be called basically at any time. Sometimes even when View Controller A is not the current view controller on the screen. Sometimes when View Controller B is displayed this function still gets called. It gets called fine. But it doesn't load viewControllerC in that case.

I've also tried the following thinking that would display from whatever the active view controller is. But that didn't work either.

self.view.window?.rootViewController?.present(viewControllerC, animated: false, completion: nil)

How can I get it to display viewControllerC when myAction is called no matter what view controller is currently being displayed?

Upvotes: 2

Views: 5765

Answers (2)

Yigit Yilmaz
Yigit Yilmaz

Reputation: 359

You presented one View Controller already and want to present second View Controller from presented View Controller, for this purpose you must call this:

UIApplication.shared.keyWindow?.rootViewController?.presentedViewController?.present(newViewController, animated: true, completion: nil)

Upvotes: 1

Optimus
Optimus

Reputation: 810

you need to get the top viewController that are currently visible in application for getting top viewController Use this code

extension UIApplication {
    class func topView(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let navController = controller as? UINavigationController {
            return topViewController(controller: navController.visibleViewController)
        }
        if let tabController = controller as? UITabBarController {
            if let selected = tabController.selectedViewController {
                return topViewController(controller: selected)
            }
        }
        if let presented = controller?.presentedViewController {
            return topViewController(controller: presented)
        }
        return controller
    }
}

Upvotes: 0

Related Questions