When I need to load a view controller from a Storyboard I like to create an extension to the view controller’s class and add a class function to it that does the work. It keeps things looking clean in the code where you use it.
I’m not sure if this is smart or dumb. I’m sure very smart people will let me know. Here’s an example.
This file contains 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 OptionsViewController { | |
class func create(completionBlock: @escaping OptionsCompletionHandler) -> UIViewController? { | |
let storyboard = UIStoryboard(name: "Options", bundle: nil) | |
guard let vc = | |
storyboard.instantiateViewController(withIdentifier:"OptionsViewController") as? OptionsViewController else { | |
return nil | |
} | |
vc.completionBlock = completionBlock | |
return vc | |
} | |
} |
Here’s how you’d use it in your code.
This file contains 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
fileprivate func displayOptionsViewController() { | |
guard let optionsViewController = OptionsViewController.create(completionBlock: optionsCompletionHandler) else { | |
NSLog("Failed to create OptionsViewController, whoops") | |
return | |
} | |
self.show(optionsViewController, sender: nil) | |
self.optionsViewController = optionsViewController as? OptionsViewController | |
} |