Skip to content

Instantly share code, notes, and snippets.

@Shinolr
Last active March 12, 2019 04:13
Show Gist options
  • Save Shinolr/e7d35518ddfe40d4999943523e2ffa57 to your computer and use it in GitHub Desktop.
Save Shinolr/e7d35518ddfe40d4999943523e2ffa57 to your computer and use it in GitHub Desktop.
Xib file reusable
class SameNameWithXibFile: UIView, XibReusable {
var contentView: UIView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
}
protocol XibReusable: AnyObject {
var contentView: UIView! { get set }
func xibSetup()
}
extension XibReusable where Self: UIView {
func xibSetup() {
contentView = loadViewFromNib()
contentView.frame = bounds
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(contentView)
}
func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as? UIView
return view!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment