iosobjective-cswiftuiviewcontroller

Instantiate and Present a viewController in Swift


Issue

I started taking a look on the Swift Programming Language, and somehow I am not able to correctly type the initialization of a UIViewController from a specific UIStoryboard.

In Objective-C I simply write:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"StoryboardName" bundle:nil];
UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"ViewControllerID"];
[self presentViewController:viewController animated:YES completion:nil];

Can anyone help me on how to achieve this on Swift?


Solution

  • 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."