Search code examples
iosswiftuiviewcontrolleruiimagepickercontrollerpresentviewcontroller

Present two UIViewControllers on top of each other programmatically in one function


I am trying to present (1) a ScrollViewController, then after that is presented, present (2) an ImagePicker. However, only the ScrollViewController is presented, not the ImagePicker afterwards.

Individually, the below code works fine, just when one follows the other, it doesn't work. I've tried including one in the completion handler, still no luck.

There are no errors displayed, except, that when the sequence occurs, the Xcode debug area is shown but completely blank with no error messages or warnings.

Questions:

What exactly is going on here that I'm missing? Why aren't both being presented? How can I ensure both the ScrollViewController and ImagePicker are displayed, one after the other?

(1) ScrollViewController:

 let storyboard = UIStoryboard(name: "Main", bundle: nil)
 let vc = storyboard.instantiateViewControllerWithIdentifier("ScrollViewControllerID") as! ScrollViewController
 self.presentViewController(vc, animated: true, completion: nil)

(2) ImagePicker:

 let imagePicker = MyImagePickerController()
 imagePicker.delegate = self
 imagePicker.sourceType = .PhotoLibrary
 imagePicker.allowsEditing = false
 imagePicker.modalTransitionStyle = UIModalTransitionStyle.CoverVertical
 self.presentViewController(imagePicker, animated: true, completion: nil)

Solution

  • A View Controller can only present one presented controller at a time. Indeed, there is a property: presentedViewController: UIViewController? that implies this. To coordinate these actions:

    A. Only present the first VC from your base VC.

    B. In the completion handler of the first presentation call, let the second VC present the final one that goes on top:

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewControllerWithIdentifier("ScrollViewControllerID") as! ScrollViewController
    self.presentViewController(vc, animated: true) {
        let imagePicker = MyImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .PhotoLibrary
        imagePicker.allowsEditing = false
        imagePicker.modalTransitionStyle = UIModalTransitionStyle.CoverVertical
        vc.presentViewController(imagePicker, animated: true, completion: nil)
    }