Skip to content

Instantly share code, notes, and snippets.

@sgr-ksmt
Last active October 20, 2021 13:33
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sgr-ksmt/a0aa3eb08b23e6df3e6e to your computer and use it in GitHub Desktop.
Save sgr-ksmt/a0aa3eb08b23e6df3e6e to your computer and use it in GitHub Desktop.
Load ViewController from Storyboard or View from Xib (These are same name.) Require : Swift 2.0
protocol NibInstantiatable {
static var NibName: String { get }
}
extension NibInstantiatable {
static var NibName: String { return String(Self) }
static func instantiate() -> Self {
return instantiateWithName(NibName)
}
static func instantiateWithOwner(owner: AnyObject?) -> Self {
return instantiateWithName(NibName, owner: owner)
}
static func instantiateWithName(name: String, owner: AnyObject? = nil) -> Self {
let nib = UINib(nibName: name, bundle: nil)
guard let view = nib.instantiateWithOwner(owner, options: nil).first as? Self else {
fatalError("failed to load \(name) nib file")
}
return view
}
}
protocol StoryboardInstantiatable {
static var StoryboardName: String { get }
}
extension StoryboardInstantiatable {
static var StoryboardName: String { return String(Self) }
static func instantiate() -> Self {
return instantiateWithName(StoryboardName)
}
static func instantiateWithName(name: String) -> Self {
let storyboard = UIStoryboard(name: name, bundle: nil)
guard let vc = storyboard.instantiateInitialViewController() as? Self else{
fatalError("failed to load \(name) storyboard file.")
}
return vc
}
}
// UIViewController
// case: same name (FooVC.swift / FooVC.storyboard)
class FooVC: UIViewController,StoryboardInstantiatable {
}
let fooVC = FooVC.instantiate()
// UIViewController
// case: different name (BarVC.swift / Sample.storyboard)
class BarVC: UIViewController,StoryboardInstantiatable {
static var StoryboardName = "Sample"
}
let barVC = BarVC.instantiate()
// UIView
// case: same name (FooView.swift / FooView.xib)
class FooView: UIView, NibInstantiatable {
}
let fooView = FooView.instantiate()
// UIView
// case: different name (BarView.swift / Sample.xib)
class BarView: UIView, NibInstantiatable {
static var NibName = "Sample"
}
let barView = BarView.instantiate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment