Skip to content

Instantly share code, notes, and snippets.

@scotteg
Last active March 20, 2019 20:47
Show Gist options
  • Save scotteg/360f1da1abcfe76e42fa980787a7e5f8 to your computer and use it in GitHub Desktop.
Save scotteg/360f1da1abcfe76e42fa980787a7e5f8 to your computer and use it in GitHub Desktop.
Extension on UIStoryboard to simplify programmatic instantiation
import UIKit
extension UIStoryboard {
enum Name: String {
case main = "Main"
case otherStuff = "OtherStuff"
}
/// Convenience method to create view controller objects that you want to manipulate and present programmatically in your application, that consults the `Name` enum to located the storyboard file and references the `UIViewController.Type` to identify the view controller and conditionally cast the instance to that type. This method creates a new instance of the specified view controller each time you call it.
/// - Warning: Before you can use this method to instantiate a view controller, you must:
/// 1. ensure that the controller is created in a storyboard file represented in the `Name` enum
/// 1. set its Storyboard ID to the view controller's `Type` in Interface Builder (e.g., `"MyViewController"`)
///
/// - Parameters:
/// - name: `Name` case representing storyboard file name where the view controller is created (`default = .main`)
/// - type: the view controller's `Type` (e.g., `MyViewController.self`)
/// - Returns: A new instance of the view controller conditionally casted as the `type` specified
static func instantiateViewController<T>(inStoryboardNamed name: Name = .main, ofType type: T.Type) -> T? {
return UIStoryboard(name: name.rawValue, bundle: nil).instantiateViewController(withIdentifier: String(describing: type.self)) as? T
}
}
@scotteg
Copy link
Author

scotteg commented Mar 20, 2019

Usage examples:

Instantiate view controller of type MyViewController in a Main.storyboard (the default) with the storyboard ID "MyViewController":

guard let controller = UIStoryboard.instantiateViewController(ofType: MyViewController.self) else { return }

Instantiate view controller of type MyViewController in a OtherStuff.storyboard with the storyboard ID "MyViewController":

guard let controller = UIStoryboard.instantiateViewController(inStoryboardNamed: .otherStuff, ofType: MyViewController.self) else { return }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment