Load view controllers effortless — Swift

Dinesh Raja
Oct 13, 2017 · 2 min read

It’s been 10 years since first iPhone released. But, we still keep writing boilerplate codes even-though we hate it. Hereafter, I will be writing about approaches and best practices I follow to prevent them.

Loading view controllers from storyboard is easier than ever.

let articlesController = ArticleViewController(from: newsStoryboard)

How would it be, If you are able to load view controllers like above code. Yes, it is that simple.

Let’s create a protocol named StoryboardLoadable. And, we will delegate the loading view controller work to StoryboardLoadable.

protocol StoryboardLoadable { }

To delegate the work to StoryboardLoadable, it must know about the identifier for every view controller in storyboard. Always, I set my view controller’s class name as identifier.

For instance, ArticleViewController’s storyboard identifier will be ArticleViewController only. It will be unique and we don’t have to come up with different names every time.

extension StoryboardLoadable where Self: UIViewController {
  static var className: String {
    return String(describing: Self.self)
  }  init(from storyboard: UIStoryboard) {
    let controller = storyboard
      .instantiateViewController(withIdentifier: Self.className)    guard let viewController = controller as? Self else {
      fatalError("Could not initialize '\(Self.className)'")
    }    self = viewController
  }
}
  • In above extension, we have one static variable for getting class name from view controller in runtime to use as storyboard identifier.
  • Also, we have custom intializer which takes UIStoryboard argument to load the view controller from.

Then, your view controller need to conform this protocol to make use of this custom intializer.

class ArticleViewController: UIViewController, StoryboardLoadable {}

To use:

let newsStoryboard = UIStoryboard(from: .news)
let articlesController = ArticleViewController(from: newsStoryboard)

Easy, right?

Tips:

  • Always use view controller’s class name as storyboard identifier.

Please support me, give your feedbacks and correct me when I’m wrong.

Dinesh Raja

Written by

Currently at DocTalk. Formerly @kiteforbusiness