Search code examples
swiftsegueuistoryboardsegue

How do I push a view controller in one case, but present it modally in another?


I have a view controller (VC3) that I want to push if accessed via one screen (VC1), but present it modally if accessed from a different screen (VC2). The destination view controller (VC3) is on its own storyboard and is embedded in a UINavigationController(which I believe is pretty important here).

In prepare(for segue) on VC1 I have this:

 if let nav = segue.destination as? UINavigationController {
     let destinationViewController = nav.topViewController as! LiftsViewController
     destinationViewController.delegate = self
   }

This presents the destination view controller (VC3) modally, which is what I want.

From VC2, the view controller (VC3) will be accessed by tapping on a cell in a table view so I want it pushed. But in prepare(for segue) on VC2 I have the same code as above because, well, I'm segueing to the same view controller which is in the UINavigationController.

I've looked at quite a few threads that address pushing vcs or presenting them modally, but can't find anything that answers how to do both with the same vc.

Thanks.


Solution

  • In this scenario let's not use the segue and push/present your VC's programmatically.

    let vc3 = (UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LiftsViewController") as? LiftsViewController)!
    vc3.delegate = self
    

    now push:

    self.navigationController?.pushViewController(vc3, animated: true)
    

    or present:

    self.presentViewController(vc3, animated: true, completion: nil)