Skip to content

Instantly share code, notes, and snippets.

@ManWithBear
Created November 22, 2018 12:10
Show Gist options
  • Save ManWithBear/225065eac4e1001aa783c84db6dda64b to your computer and use it in GitHub Desktop.
Save ManWithBear/225065eac4e1001aa783c84db6dda64b to your computer and use it in GitHub Desktop.
Smarty way to init xib views inside other xibs
import UIKit
/// thanks to Badoo
/// https://github.com/badoo/Chatto/blob/master/ChattoAdditions/Source/Input/ReusableXibView.swift
@objc open class ReusableXibView: UIView {
func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: type(of: self).nibName(), bundle: bundle)
let view = nib.instantiate(withOwner: nil, options: nil).first as! UIView
return view
}
override open func awakeAfter(using aDecoder: NSCoder) -> Any? {
if self.subviews.count > 0 {
return self
}
let bundle = Bundle(for: type(of: self))
if let loadedView = bundle.loadNibNamed(type(of: self).nibName(), owner: nil, options: nil)?.first as? UIView {
loadedView.frame = frame
loadedView.autoresizingMask = autoresizingMask
loadedView.translatesAutoresizingMaskIntoConstraints = translatesAutoresizingMaskIntoConstraints
for constraint in constraints {
let firstItem = constraint.firstItem === self ? loadedView : constraint.firstItem
let secondItem = constraint.secondItem === self ? loadedView : constraint.secondItem
loadedView.addConstraint(NSLayoutConstraint(item: firstItem as Any, attribute: constraint.firstAttribute, relatedBy: constraint.relation, toItem: secondItem, attribute: constraint.secondAttribute, multiplier: constraint.multiplier, constant: constraint.constant))
}
return loadedView
} else {
return nil
}
}
class func nibName() -> String {
assert(false, "Must be overriden")
return ""
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment