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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With