Instantiate and Present a viewController in Swift Instantiate and Present a viewController in Swift ios ios

Instantiate and Present a viewController in Swift


This answer was last revised for Swift 5.4 and iOS 14.5 SDK.


It's all a matter of new syntax and slightly revised APIs. The underlying functionality of UIKit hasn't changed. This is true for a vast majority of iOS SDK frameworks.

let storyboard = UIStoryboard(name: "myStoryboardName", bundle: nil)let vc = storyboard.instantiateViewController(withIdentifier: "myVCID")self.present(vc, animated: true)

Make sure to set myVCID inside the storyboard, under "Storyboard ID."


For people using @akashivskyy's answer to instantiate UIViewController and are having the exception:

fatal error: use of unimplemented initializer 'init(coder:)' for class

Quick tip:

Manually implement required init?(coder aDecoder: NSCoder) at your destination UIViewController that you are trying to instantiate

required init?(coder aDecoder: NSCoder) {    super.init(coder: aDecoder)}

If you need more description please refer to my answer here


This link has both the implementations:

Swift:

let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ViewController") as UIViewControllerself.presentViewController(viewController, animated: false, completion: nil)

Objective C

UIViewController *viewController = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"ViewController"];

This link has code for initiating viewcontroller in the same storyboard

/* Helper to Switch the View based on StoryBoard @param StoryBoard ID  as String*/func switchToViewController(identifier: String) {    let viewController = self.storyboard?.instantiateViewControllerWithIdentifier(identifier) as! UIViewController    self.navigationController?.setViewControllers([viewController], animated: false)}