Skip to content

Instantly share code, notes, and snippets.

@leojkwan
Created July 16, 2018 21:38
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 leojkwan/b125a7049baecd7e307cc8f3b1d00f33 to your computer and use it in GitHub Desktop.
Save leojkwan/b125a7049baecd7e307cc8f3b1d00f33 to your computer and use it in GitHub Desktop.
// MARK: Support for instantiation from NIB
public extension HasNib where Self: UIView {
static var nib: UINib {
return UINib(nibName: String(describing: self), bundle: Bundle(for: self))
}
// Adds content loaded from the nib to the end of the
// receiver's list of subviews and adds constraints automatically.
func loadNibContent() {
let layoutAttributes: [NSLayoutAttribute] = [.top, .leading, .bottom, .trailing]
for view in Self.nib.instantiate(withOwner: self, options: nil) {
if let view = view as? UIView {
view.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(view)
layoutAttributes.forEach { attribute in
self.addConstraint(
NSLayoutConstraint(
item: view,
attribute: attribute,
relatedBy: .equal,
toItem: self,
attribute: attribute,
multiplier: 1,
constant: 0.0))
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment