Last active
December 27, 2020 14:52
-
-
Save srstanic/90348ef18d592c4177e2b6a0daf4c205 to your computer and use it in GitHub Desktop.
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 | |
| extension UIViewController { | |
| /// Creates an instance of `ViewControllerType` defined in a storyboard. | |
| /// | |
| /// The setup for this method to work is the following: | |
| /// 1. The storyboard needs to have a single view controller of the type `ViewControllerType` | |
| /// 2. This view controller needs to be set as the initial view controller | |
| /// 3. The name of the view controller needs to match the name of the storyboard and end with "ViewController". | |
| /// e.g. Some.storyboard and SomeViewController | |
| static func initFromStoryboard<ViewControllerType: UIViewController>() -> ViewControllerType { | |
| let bundle = Bundle(for: self) | |
| let name = String(describing: self).replacingOccurrences(of: "ViewController", with: "") | |
| let storyboard = UIStoryboard(name: name, bundle: bundle) | |
| guard let viewController = storyboard.instantiateInitialViewController() as? ViewControllerType else { | |
| let error = """ | |
| ViewController of type \(self) failed to instantiate. | |
| Check if the ViewController is set as initial in the Storyboard | |
| and that it's set to a correct custom class. | |
| """ | |
| fatalError(error) | |
| } | |
| return viewController | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment