Created
July 13, 2019 09:14
-
-
Save ppth0608/572132c1161019d7e493237e129c5d86 to your computer and use it in GitHub Desktop.
How to make UIViewController when using storyboard
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
enum Storyboard { | |
case main | |
var filename: String { | |
switch self { | |
case .main: return "Main" | |
} | |
} | |
} | |
protocol StoryboardIdentifiable { | |
static var storyboardIdentifier: String { get } | |
} | |
extension UIViewController: StoryboardIdentifiable { | |
static var storyboardIdentifier: String { | |
return String(describing: self) | |
} | |
} | |
extension UIStoryboard { | |
convenience init(storyboard: Storyboard, bundle: Bundle? = nil) { | |
self.init(name: storyboard.filename, bundle: bundle) | |
} | |
class func storyboard(_ storyboard: Storyboard, bundle: Bundle? = nil) -> UIStoryboard { | |
return UIStoryboard(name: storyboard.filename, bundle: bundle) | |
} | |
func instantiateViewController<T: UIViewController>() -> T { | |
guard let viewController = instantiateViewController(withIdentifier: T.storyboardIdentifier) as? T else { | |
fatalError("Couldn't instantiate view controller with identifier \(T.storyboardIdentifier) ") | |
} | |
return viewController | |
} | |
} | |
protocol UIViewControllerCreatable { } | |
extension UIViewControllerCreatable where Self: UIViewController { | |
static func create(of storyboard: Storyboard) -> Self { | |
return UIStoryboard(storyboard: storyboard).instantiateViewController() | |
} | |
} | |
extension UIViewController: UIViewControllerCreatable { } | |
/////// | |
/Usage/ | |
/////// | |
let viewController = MainViewController.create(of: .main) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment