Skip to content

Instantly share code, notes, and snippets.

@chanonly123
Last active May 27, 2020 08:59
Show Gist options
  • Save chanonly123/3dfe5398d591d2c139a5d9f66bef4012 to your computer and use it in GitHub Desktop.
Save chanonly123/3dfe5398d591d2c139a5d9f66bef4012 to your computer and use it in GitHub Desktop.
Designable view from xib, with optimisation
@IBDesignable
class UIViewXib: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
loadViewFromNib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadViewFromNib()
}
private func loadViewFromNib() {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
if let view = nib.instantiate(withOwner: self, options: nil).first as? UIView {
let consts = view.constraints
view.subviews.forEach {
$0.removeFromSuperview()
addSubview($0)
}
consts.forEach {
let firstItem = $0.firstItem === view ? self : $0.firstItem
let secondItem = $0.secondItem === view ? self : $0.secondItem
addConstraint(.init(item: firstItem!, attribute: $0.firstAttribute, relatedBy: $0.relation, toItem: secondItem!, attribute: $0.secondAttribute, multiplier: $0.multiplier, constant: $0.constant))
}
}
// low priority default height constraint
let heightConst = heightAnchor.constraint(equalToConstant: 100)
heightConst.priority = .init(1)
heightConst.isActive = true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment