Last active
November 30, 2018 18:33
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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