Bartłomiej Semańczyk Bartłomiej Semańczyk - 7 months ago 16
Swift Question

How to return two different presentation controllers for two different controllers from extension of UIViewController?

This is my extension:

extension UIViewController: UIViewControllerTransitioningDelegate {

func presentAssignBookToClassesViewController(controller: BWAssignBookToClassesViewController) {

controller.modalPresentationStyle = .Custom
controller.transitioningDelegate = self
controller.preferredContentSize = CGSizeMake(500, 575)

presentViewController(controller, animated: true, completion: nil)
}

func presentSettingsStoryboard() {

if let settingsController = UIStoryboard(name: "TeacherSettingsStoryboard", bundle: nil).instantiateInitialViewController() {

settingsController.modalPresentationStyle = .Custom
settingsController.transitioningDelegate = self
settingsController.preferredContentSize = CGSizeMake(500, 575)

presentViewController(settingsController, animated: true, completion: nil)
}
}

//MARK: - UIViewControllerTransitioningDelegate

public func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? {

return BWOverlayPresentationController(presentedViewController: presented, presentingViewController: presenting)
}
}


Within
presentationControllerForPresentedViewController:
I need to return either
BWOverlayPresentationController
or
BWSettingsPresentationController
depending on what mwthod was called. How to achieve this?

Answer

You can simply distinguish them via restorationIdentifier (you can set this simply using storyboard):

//MARK: - UIViewControllerTransitioningDelegate

public func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? {

    if presented.restorationIdentifier == BWSettingsRestorationIdentifier {
        return BWSettingsPresentationController(presentedViewController: presented, presentingViewController: presenting)
    } else {
        return BWOverlayPresentationController(presentedViewController: presented, presentingViewController: presenting)
    }
}