Created
August 15, 2020 17:23
-
-
Save lalkrishna/e3f0ecef5be315bf5ae240f09eb768f3 to your computer and use it in GitHub Desktop.
UIStoryboard Extension for Easy Instantiate Viewcontrollers [Swift]
This file contains 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
enum Storyboard: String { | |
case main = "Main", | |
onboarding = "Onboarding" | |
} | |
protocol Instantiatable { | |
static var storyboard: Storyboard { get } | |
static func instantiate() -> Self | |
} | |
extension Instantiatable where Self: UIViewController { | |
static func instantiate() -> Self { | |
// swiftlint:disable force_cast | |
UIStoryboard(storyboard).instantiateViewController(withIdentifier: String(describing: Self.self)) as! Self | |
} | |
} | |
extension UIStoryboard { | |
convenience init(_ storyboard: Storyboard) { | |
self.init(name: storyboard.rawValue, bundle: nil) | |
} | |
} | |
// Usage: | |
class ViewController: UIViewController, Instantiatable { | |
static var storyboard: Storyboard = .main | |
} | |
// Get Instance by: | |
let vc = ViewController.instantiate() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You have to declare both storyboard in struct and, each VC should conforms to
Instantiatable
protocol.