Skip to content

Instantly share code, notes, and snippets.

@JeremyXue77
Created March 29, 2020 04:49
Show Gist options
  • Select an option

  • Save JeremyXue77/a5147fdf8f0ef3db74958cbfa4a2b8dd to your computer and use it in GitHub Desktop.

Select an option

Save JeremyXue77/a5147fdf8f0ef3db74958cbfa4a2b8dd to your computer and use it in GitHub Desktop.
protocol NibOwnerLoadable: AnyObject {
static var nib: UINib { get }
}
// MARK: - Default implmentation
extension NibOwnerLoadable {
static var nib: UINib {
UINib(nibName: String(describing: self), bundle: Bundle(for: self))
}
}
// MARK: - Supporting methods
extension NibOwnerLoadable where Self: UIView {
func loadNibContent() {
guard let views = Self.nib.instantiate(withOwner: self, options: nil) as? [UIView],
let contentView = views.first else {
fatalError("Fail to load \(self) nib content")
}
self.addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.topAnchor.constraint(equalTo: topAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
contentView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
contentView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment