Skip to content

Instantly share code, notes, and snippets.

@samdods
Created August 23, 2016 14:50
Show Gist options
  • Save samdods/cd13fa68fcf58158b79c1edb3f11341b to your computer and use it in GitHub Desktop.
Save samdods/cd13fa68fcf58158b79c1edb3f11341b to your computer and use it in GitHub Desktop.
This is the best way to instantiate a view controller from a storyboard in Swift
//
// UIViewController+StoryboardLoading.swift
// Sam Dods on 23/08/2016.
//
import UIKit
/// Protocol to be extended with implementations
protocol UIViewControllerLoading {}
/// Extend UIViewController to declare that it includes storyboard loading functionality
extension UIViewController : UIViewControllerLoading {}
/// Protocol implementation
extension UIViewControllerLoading where Self : UIViewController {
/**
Creates a new instance of the class on which this method is invoked,
instantiated from a storyboard of the given name. If no storyboard
name is given then a storyboard with the name of the class is used.
- parameter storyboardNameOrNil: The name of the storyboard to load
from, or nil to indicate the storyboard with the name of the class
should be used.
- returns: A new instance of the class, loaded from a storyboard.
*/
static func loadFromStoryboard(storyboardNameOrNil: String? = nil) -> Self {
let nibName = storyboardNameOrNil ?? self.className
let storyboard = UIStoryboard(name: nibName, bundle: nil)
return storyboard.instantiateInitialViewController() as! Self
}
static private var className: String {
let className = "\(self)"
let components = className.characters.split{$0 == "."}.map ( String.init )
return components.last!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment