Instantiate and Present a viewController in Swift

E-Riddie picture E-Riddie · Jun 4, 2014 · Viewed 327.2k times · Source

Issue

I started taking a look of the new Swift on Xcode 6, and I tried some demo projects and tutorials. Now I am stuck at:

Instantiating and then presenting a viewController from a specific storyboard

Objective-C Solution

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"myStoryboardName" bundle:nil];
UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"myVCID"];
[self presentViewController:vc animated:YES completion:nil];

How to achieve this on Swift?

Answer

akashivskyy picture akashivskyy · Jun 4, 2014

This answer was last revised for Swift 5.2 and iOS 13.4 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)

If you're having problems with init(coder:), please refer to EridB's answer.