Skip to content

Instantly share code, notes, and snippets.

@aryaxt
Last active December 17, 2015 02:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aryaxt/6d219ff686384535fde4 to your computer and use it in GitHub Desktop.
Save aryaxt/6d219ff686384535fde4 to your computer and use it in GitHub Desktop.
Multiple Storyboard Usage
@interface UIStoryboard (Additions)
- (id __nullable)tryInstantiateViewControllerWithIdentifier:(NSString * __nonnull)identifier;
@end
@implementation UIStoryboard (Additions)
- (id)tryInstantiateViewControllerWithIdentifier:(NSString *)identifier {
@try {
return [self instantiateViewControllerWithIdentifier:identifier];
}
@catch (NSException *exception) {
return nil;
}
}
@end
private var storyboardIdForControllers = [String: String]()
private var allStoryboardIds = [String]() // Either manualy add them or use NSFilemanager and read all files with .storyboard extension
extension UIStoryboard {
public class func instantiateViewController <T: UIViewController>(type: T.Type) -> T {
let viewControllerId = String(type)
if let storyboardId = storyboardIdForControllers[viewControllerId] {
let storyboard = UIStoryboard(name: storyboardId, bundle: nil)
return storyboard.instantiateViewControllerWithIdentifier(viewControllerId) as! T
}
else {
for storyboardId in allStoryboardIds {
let storyboard = UIStoryboard(name: storyboardId, bundle: nil)
if let viewController = storyboard.tryInstantiateViewControllerWithIdentifier(viewControllerId) {
storyboardIdForControllers[viewControllerId] = storyboardId
return viewController as! T
}
}
fatalError("Could not instantiate Viewcontroller with identifier: \(viewControllerId)")
}
}
}
extension UIViewController {
public class func instantiateFromStoryBoard() -> Self {
return UIStoryboard.instantiateViewController(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment