Skip to content

Instantly share code, notes, and snippets.

@josipbernat
Last active October 27, 2020 10:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josipbernat/9a56042fd3c8cf18abd6771ace998890 to your computer and use it in GitHub Desktop.
Save josipbernat/9a56042fd3c8cf18abd6771ace998890 to your computer and use it in GitHub Desktop.
Instating view controller from storyboard in easier way
extension UIStoryboard {
func instantiateViewController<T: UIViewController>() -> T {
let viewController = self.instantiateViewController(withIdentifier: T.className)
guard let typedViewController = viewController as? T else {
fatalError("Unable to cast view controller of type (\(type(of: viewController))) to (\(T.className))")
}
return typedViewController
}
}
extension NSObject {
static var className: String {
return String(describing: self)
}
}
// Example
// Inside storyboard add new UIViewController, set custom class and set StoryboardID to match class.
// For example I'll use UIViewController's subclass named: ProductDetailsViewController
// When you want to instante new ProductDetailsViewController you have two options (cases):
// 1. Case where current viewController and ProductDetailsViewController share the same UIStoryboard file
let controller: ProductDetailsViewController = self.storyboard!.instantiateViewController()
// 2. Case where current viewController and ProductDetailsViewController are in different UIStoryboard files
let controller: ProductDetailsViewController = UIStoryboard(name: "storyboard_name", bundle: nil).instantiateViewController()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment