Skip to content

Instantly share code, notes, and snippets.

@josippetric
Last active June 18, 2020 09:16
Show Gist options
  • Select an option

  • Save josippetric/b8815952527e5088f01538670880358a to your computer and use it in GitHub Desktop.

Select an option

Save josippetric/b8815952527e5088f01538670880358a to your computer and use it in GitHub Desktop.
Storyboarded - Protocol to create ViewControllers from a storyboard
import UIKit
protocol Storyboarded {
static func instantiate(storyboardName: String?) -> Self
}
extension Storyboarded where Self: UIViewController {
static func instantiate(storyboardName: String?) -> Self {
// this pulls out "MyApp.MyViewController"
let fullName = NSStringFromClass(self)
let className = fullName.components(separatedBy: ".")[1]
// load our storyboard
let storyboard = UIStoryboard(name: storyboardName ?? "Main", bundle: Bundle.main)
// instantiate a view controller with that identifier, and force cast as the type that was requested
return storyboard.instantiateViewController(withIdentifier: className) as! Self
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment