Last active
October 11, 2017 18:47
-
-
Save mjhassan/2fdbc5984bcb20d215ba0d6692c35789 to your computer and use it in GitHub Desktop.
Generic Swift methods to load ViewControllers from UIStoryboard
This file contains hidden or 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
| import UIKit | |
| fileprivate enum Storyboard : String { | |
| case main = "Main" // storyboard name | |
| } | |
| fileprivate extension UIStoryboard { | |
| static func loadFromMain<T>(_ identifier: String) -> T { | |
| return load(from: .main, identifier: identifier) | |
| } | |
| static func load<T>(from storyboard: Storyboard, identifier: String) -> T { | |
| let uiStoryboard = UIStoryboard(name: storyboard.rawValue, bundle: nil) | |
| return uiStoryboard.instantiateViewController(withIdentifier: identifier) as! T | |
| } | |
| } | |
| /** | |
| Public enum for all view controllers with corresponding storyboar id | |
| - type: String | |
| */ | |
| public enum Screen: String { | |
| case Login = "LoginViewController" | |
| case Home = "HomeViewController" | |
| case Contact = "ContactViewController" | |
| case Gallery = "GalleryViewController" | |
| } | |
| /** | |
| Stroyboard extension for loading view controllers | |
| */ | |
| extension UIStoryboard { | |
| static func loadViewController<T>(screen: Screen, asClass: T.Type) -> T { | |
| return loadFromMain(screen.rawValue) | |
| } | |
| static func loadViewController<T>(screen: Screen) -> T { | |
| return loadFromMain(screen.rawValue) | |
| } | |
| } | |
| /* | |
| // use it like | |
| let vc1 = UIStoryboard.loadViewController(Screen.Login, asClass: LoginViewController.self) | |
| // or | |
| let vc2: HomeViewController = UIStoryboard.loadViewController(Screen.Home) | |
| // did you noticed? you didn't even need to initialize the storyboard ;) | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment