Skip to content

Instantly share code, notes, and snippets.

@JasonCanCode
Last active November 30, 2018 18:33
Show Gist options
  • Save JasonCanCode/78006e7bf5c670376eda5d7fee0ad6c4 to your computer and use it in GitHub Desktop.
Save JasonCanCode/78006e7bf5c670376eda5d7fee0ad6c4 to your computer and use it in GitHub Desktop.
Easily generate a new instance of a View Controller that exists within a storyboard
import UIKit
struct StoryboardHelper {
/// Assumes that the storyboard identifier for the View Controller class provided matches its name and that it has been added to the `storyboardNameForViewController` switch statement.
static func new<T>() -> T? {
let nibName = String(describing: T.self)
let storyboardName = storyboardNameForViewController(named: nibName)
return getViewController(named: nibName, fromStoryboardNamed: storyboardName) as? T
}
private static func getViewController(named name: String, fromStoryboardNamed storyboardName: String) -> UIViewController {
let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
let targetController = storyboard.instantiateViewController(withIdentifier: name)
return targetController
}
// MARK: View Controller Mapping
private static func storyboardNameForViewController(named name: String) -> String {
switch name {
// TODO: View controllers must be added here for mapping. Below is an example of
// `case "ViewControllerName", ...: return "StoryboardName"`
case "ExampleFeatureViewController", "ExampleFeatureDetailViewController":
return "ExampleFeature"
default:
return "Main"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment