How to access my custom UIPresentationController from within presented controller?

1.5k Views Asked by At

This is how I perform transitioning:

extension UIViewController: UIViewControllerTransitioningDelegate {

    public func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return OverlayPresentationController(presentedViewController: presented, presenting: presenting)
    }

    func presentOverlayController(_ controller: UIViewController) {

        controller.modalPresentationStyle = .custom
        controller.transitioningDelegate = self

        present(controller, animated: true)
    }
} 

And then within my presented controller (AlertVC) at some point I need to access its presentation controller:

print(presentationController as? OverlayPresentationController) //nil
print(presentationController) //is ok, UIPresentationController

Why?

Presenting:

let controller = AlertVC.instantiate()
controller.update()
presentOverlayController(controller)

class AlertVC: UIViewController {

    class func instantiate() -> AlertVC {
        return UIStoryboard(name: "Alert", bundle: Bundle(for: LoginVC.classForCoder())).instantiateInitialViewController() as! AlertVC
    }

    func update() {
        _ = view

        print(presentationController as? OverlayPresentationController) //nil
    }
}
1

There are 1 best solutions below

4
On

You get the view controller that is presenting the current view controller by calling presentingViewController

// The view controller that presented this view controller (or its farthest ancestor.)
self.presentingViewController 

If your presenting view controller is in a navigation controller that returns a UINavigationController. You can get the view controller you need like so:

let presentingNVC = self.presentingViewController as? UINavigationViewController
let neededVC = presentingNVC.viewControllers.last as? NeededViewController