Skip to content

Instantly share code, notes, and snippets.

@rtimpone
Created January 5, 2019 18:08
Show Gist options
  • Save rtimpone/e47a0c83c52c7213764c7cd2719bee44 to your computer and use it in GitHub Desktop.
Save rtimpone/e47a0c83c52c7213764c7cd2719bee44 to your computer and use it in GitHub Desktop.
import UIKit
protocol NibBased {
static var nibName: String { get }
}
extension NibBased {
static var nibName: String {
return String(describing: self)
}
}
extension NibBased where Self: UIView {
static func fromNib() -> Self {
let bundle = Bundle(for: self)
guard let nibs = bundle.loadNibNamed(nibName, owner: nil, options: nil) else {
fatalError("No nibs named '\(nibName)' were found in this bundle")
}
if nibs.count > 1 {
fatalError("More than one nib named '\(nibName)' was found in this bundle")
}
guard let instance = nibs.first as? Self else {
fatalError("The view found in nib named '\(nibName)' was not the correct type, '\(self)'")
}
return instance
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment