Skip to content

Instantly share code, notes, and snippets.

@adamgraham
Last active June 16, 2019 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamgraham/2ade0b22724963d3a702d9192283cd64 to your computer and use it in GitHub Desktop.
Save adamgraham/2ade0b22724963d3a702d9192283cd64 to your computer and use it in GitHub Desktop.
A utility iOS protocol that allows for easy instantiation of classes that are associated with a Nib.
/// A type that can be loaded from an associated nib.
protocol NibLoadable: class {
/// The name of the nib for the loadable class.
static var nibName: String { get }
/// The bundle the nib is contained within for the loadable class.
static var nibBundle: Bundle { get }
}
extension NibLoadable {
static var nibName: String {
// defaults to the name of the class
return String(describing: Self.self)
}
static var nibBundle: Bundle {
// defaults to the name of the class
return Bundle(for: Self.self)
}
/// An instance of the nib for the loadable class.
static var nib: UINib {
return UINib(nibName: Self.nibName, bundle: self.nibBundle)
}
}
extension NibLoadable where Self: UIView {
/// Instantiates and returns the root view of the nib.
private func instantiate<T: UIView>() -> T {
guard let instance = Self.nib.instantiate(withOwner: self, options: nil).first as? T else {
fatalError("Failed to instantiate nib named '\(Self.nibName)'")
}
return instance
}
/// Instantiates the view from the nib, and adds it as a subview to the current instance
/// constrained to all sides.
func loadFromNib() {
let view = instantiate()
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
view.topAnchor.constraint(equalTo: self.topAnchor, constant: 0.0),
view.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0.0),
view.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0.0),
view.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0.0)
])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment