Last active
October 27, 2020 10:37
-
-
Save josipbernat/9a56042fd3c8cf18abd6771ace998890 to your computer and use it in GitHub Desktop.
Instating view controller from storyboard in easier way
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
extension UIStoryboard { | |
func instantiateViewController<T: UIViewController>() -> T { | |
let viewController = self.instantiateViewController(withIdentifier: T.className) | |
guard let typedViewController = viewController as? T else { | |
fatalError("Unable to cast view controller of type (\(type(of: viewController))) to (\(T.className))") | |
} | |
return typedViewController | |
} | |
} | |
extension NSObject { | |
static var className: String { | |
return String(describing: self) | |
} | |
} | |
// Example | |
// Inside storyboard add new UIViewController, set custom class and set StoryboardID to match class. | |
// For example I'll use UIViewController's subclass named: ProductDetailsViewController | |
// When you want to instante new ProductDetailsViewController you have two options (cases): | |
// 1. Case where current viewController and ProductDetailsViewController share the same UIStoryboard file | |
let controller: ProductDetailsViewController = self.storyboard!.instantiateViewController() | |
// 2. Case where current viewController and ProductDetailsViewController are in different UIStoryboard files | |
let controller: ProductDetailsViewController = UIStoryboard(name: "storyboard_name", bundle: nil).instantiateViewController() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment