iOS Notes 19: How to push and present to ViewController programmatically? [How to switch VC]

Kuray Ogun
FreakyCoder Software Blog

--

Updated: Jan 27, 2020

Switch between VC is really important for every application. You can switch between VC with three options :

  • Segue
  • Present ( Programmatically )
  • Push ( Programmatically )

Present View Controller

Code:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "LoginVC")
self.present(controller, animated: true, completion: nil)
// Safe Present
if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginVC") as? LoginVC
{
present(vc, animated: true, completion: nil)
}

Gist:

Push View Controller

Code:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "MainVC") as UIViewController
navigationController?.pushViewController(vc, animated: true)
// Safe Push VC
if let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MainVC") as? JunctionDetailsVC {
if let navigator = navigationController {
navigator.pushViewController(viewController, animated: true)
}
}

Gist:

If you are using TBC ( TabBarController ), you should use Push as a switch between VC.

If you have any question, ask me :)

--

--