Categories
Development iOS Work Note

Work Note: Loading View Controllers from a Storyboard

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.

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.

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
}

By Rob Fahrni

Husband / Father / Developer