Skip to content

Instantly share code, notes, and snippets.

@serhii-londar
Last active April 15, 2019 11:17
Show Gist options
  • Save serhii-londar/de3d1eb26d6bb098c0c564b43a0bfee5 to your computer and use it in GitHub Desktop.
Save serhii-londar/de3d1eb26d6bb098c0c564b43a0bfee5 to your computer and use it in GitHub Desktop.
Pure protocol factory for Interface Builder-based views(https://blog.hal.codes/ib-constructible)
protocol IBConstructible: AnyObject {
static var nibName: String { get }
static var bundle: Bundle { get }
}
extension IBConstructible {
static var nibName: String {
return String(describing: Self.self)
}
static var bundle: Bundle {
return Bundle(for: Self.self)
}
}
extension IBConstructible where Self: UIViewController {
static var fromNib: Self {
let storyboard = UIStoryboard(name: nibName, bundle: bundle)
guard let viewController = storyboard.instantiateInitialViewController() as? Self else {
fatalError("Missing view controller in \(nibName).storyboard")
}
return viewController
}
}
extension IBConstructible where Self: UIView {
static var fromNib: Self {
let xib = UINib(nibName: nibName, bundle: bundle)
guard let view = xib.instantiate(withOwner: nil, options: nil).first as? Self else {
fatalError("Missing view in \(nibName).xib")
}
return view
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment