Skip to content

Instantly share code, notes, and snippets.

@srstanic
Last active December 27, 2020 14:52
Show Gist options
  • Select an option

  • Save srstanic/90348ef18d592c4177e2b6a0daf4c205 to your computer and use it in GitHub Desktop.

Select an option

Save srstanic/90348ef18d592c4177e2b6a0daf4c205 to your computer and use it in GitHub Desktop.
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