Skip to content

Instantly share code, notes, and snippets.

@tvidenov
Created March 17, 2022 06:39
Show Gist options
  • Save tvidenov/002eb77d2a012dc9311bf742754d79b7 to your computer and use it in GitHub Desktop.
Save tvidenov/002eb77d2a012dc9311bf742754d79b7 to your computer and use it in GitHub Desktop.
Storyboarded
import UIKit
protocol Storyboarded {
static func instantiate() -> Self
}
extension Storyboarded where Self: UIViewController {
static func instantiate() -> Self {
// this pulls out "MyApp.MyViewController"
let fullName = NSStringFromClass(self)
// this splits by the dot and uses everything after, giving "MyViewController"
let className = fullName.components(separatedBy: ".")[1]
// load our storyboard
let storyboard = UIStoryboard(name: "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