-
-
Save onmyway133/a5e1fb8d967343e837d3 to your computer and use it in GitHub Desktop.
Multiple Storyboard Usage
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
@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