Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 518
E-Riddie Avatar asked Jun 04 '14 11:06

E-Riddie


People also ask

How do you instantiate a storyboard?

In the Storyboard, select the view controller that you want to instantiate in code. Make sure the yellow circle is highlighted, and click on the Identity Inspector. Set the custom class as well as the field called "Storyboard ID". You can use the class name as the Storyboard ID.


2 Answers

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

like image 141
akashivskyy Avatar answered Oct 18 '22 19:10

akashivskyy


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

like image 24
E-Riddie Avatar answered Oct 18 '22 20:10

E-Riddie