Present ViewController in Swift

With his short Swift code example I am going to share with you how to present user with a new ViewController instantiated from the Main storyboard.

The below code example needs to be ran from a ViewController over which you would like to present another/target ViewController. The presented View Controller will appear on top of current one.

Make sure you provide correct identifier of your target ViewController or other wise it will not work. In my case I am presenting a ViewController that has an Identifier set to “RegisterAccountViewController”.

Present ViewController Code Example in Swift

For the below code to work you, will need to create a new ViewController using the Storyboard. Then you can instantiate it using the Storyboard and present it to user the following way:

let registerViewController = self.storyboard?.instantiateViewController(withIdentifier: "RegisterAccountViewController") as! RegisterAccountViewController

self.present(registerViewController, animated: true)

Present ViewController with XIB Interface

For the below code example to work, you will need to create a new user interface file using XIB and set its File Owner to the ViewController you need. In my case I have created a new ViewController and a XIB file with the same name NewViewController.

To present ViewController which works with XIB file you can use the following example:

// Register Nib
let newViewController = NewViewController(nibName: "NewViewController", bundle: nil)

// Present View "Modally"
self.present(newViewController, animated: true, completion: nil)


Wrap ViewController into NavigationController and Present

To present a ViewController in a NavigationController you can wrap ViewController into a NavigationController as it is in the example below. Then present NavigationController which contains ViewController.

// Register Nib    
let newViewController = CustomSignupViewController(nibName: "CustomSignupViewController", bundle: nil)
let navigationController = UINavigationController(rootViewController: newViewController)
// Present View "Modally"
self.present(navigationController, animated: true, completion: nil)


Check out the below video courses to learn more about Mobile App Development for iOS platform with Swift.

[raw_html_snippet id=”cookbookpagecoursesheader”]

Unit Testing Swift Mobile App

Apply Test-Driven Development(TDD) process to iOS mobile app development in Swift Preview this video course.