How to Navigate from one View Controller to another using Swift How to Navigate from one View Controller to another using Swift swift swift

How to Navigate from one View Controller to another using Swift


Create a swift file (SecondViewController.swift) for the second view controllerand in the appropriate function type this:

let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as SecondViewControllerself.navigationController.pushViewController(secondViewController, animated: true)


Swift 2+

let mapViewControllerObj = self.storyboard?.instantiateViewControllerWithIdentifier("MapViewControllerIdentifier") as? MapViewControllerself.navigationController?.pushViewController(mapViewControllerObj!, animated: true)

Swift 4

let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "IKDetailVC") as? IKDetailVCself.navigationController?.pushViewController(vc!, animated: true)


In my experience navigationController was nil so I changed my code to this:

let next = self.storyboard?.instantiateViewControllerWithIdentifier("DashboardController") as! DashboardControllerself.presentViewController(next, animated: true, completion: nil)

Don't forget to set ViewController StoryBoard Id in StoryBoard -> identity inspector


If you don't want the back button to appear (which was my case, because I wanted to present after a user logged in) here is how to set the root of the nav controller:

let vc = self.storyboard?.instantiateViewControllerWithIdentifier("YourViewController") as! YourViewController        let navigationController = UINavigationController(rootViewController: vc)        self.presentViewController(navigationController, animated: true, completion: nil)