Skip to content

Instantly share code, notes, and snippets.

@fethica
Created November 24, 2022 06:35
Show Gist options
  • Save fethica/869d2f70679b710c7b1f4b4237a51fbb to your computer and use it in GitHub Desktop.
Save fethica/869d2f70679b710c7b1f4b4237a51fbb to your computer and use it in GitHub Desktop.
Create controllers programmatically from the Main Storyboard
import UIKit
struct Storyboard<T: UIViewController> {
static var storyboardName: String {
return String(describing: T.self)
}
static var viewController: T {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
guard let vc = storyboard.instantiateViewController(withIdentifier: Self.storyboardName) as? T else {
fatalError("Could not get controller from Storyboard: \(Self.storyboardName)")
}
return vc
}
}
// Usage (Storyboard ID must match the UIViewController class name)
let myVC = Storyboard.viewController as MyViewController
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment