Skip to content

Instantly share code, notes, and snippets.

@fewlinesofcode
Created July 16, 2018 05:29
Show Gist options
  • Save fewlinesofcode/4ca1c8cd6824bffb03e5715ba4a7b794 to your computer and use it in GitHub Desktop.
Save fewlinesofcode/4ca1c8cd6824bffb03e5715ba4a7b794 to your computer and use it in GitHub Desktop.
Load UIView from NIB
class <#ClassName#>: UIView {
// Do not forget to wire to XIB
@IBOutlet var view: UIView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadFromNib()
}
init() {
super.init(frame: CGRect())
loadFromNib()
}
override init(frame: CGRect) {
super.init(frame: frame)
loadFromNib()
}
fileprivate func loadFromNib() {
view = Bundle.main.loadNibNamed("<#ClassName#>", owner: self, options: nil)?.first as! UIView
view.translatesAutoresizingMaskIntoConstraints = false
addSubview(view)
let views: [String : Any] = ["view": view]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: .alignAllCenterX, metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: .alignAllCenterY, metrics: nil, views: views))
// Any other setup
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment