Skip to content

Instantly share code, notes, and snippets.

@gravicle
Last active October 17, 2016 19:19
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 gravicle/f21429a2be96b4da6663dac65d6fd84e to your computer and use it in GitHub Desktop.
Save gravicle/f21429a2be96b4da6663dac65d6fd84e to your computer and use it in GitHub Desktop.
Abstract class allowing UIViews to be programmatically initialized while using IB internally for layout
import UIKit
/// Allows loading view from Nibs named the same as the class.
class IBLoadableView: UIView {
fileprivate var view: UIView!
convenience init() {
self.init(frame: CGRect.zero)
}
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
setup()
}
}
// MARK: - Setup
extension IBLoadableView {
/// Any setup after initiaization can be done here. Always call super at some point.
func setup() {
backgroundColor = .clear
}
}
// MARK: - XIB Loading
fileprivate extension IBLoadableView {
func xibSetup() {
view = loadViewFromNib(named: nameOfClass)
addSubview(view)
view.layoutWithEdgesEqualToSuperView()
awakeFromNib()
}
func loadViewFromNib(named name: String) -> UIView {
let bundle = Bundle(for: type(of: self))
if nibExists(withName: name, in: bundle) {
let nib = UINib(nibName: name, bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
return view
} else if let superclass = superclass {
return loadViewFromNib(named: superclass.nameOfClass)
} else {
fatalError("No NIB found: \(nameOfClass)")
}
}
func nibExists(withName name: String, in bundle: Bundle) -> Bool {
return bundle.path(forResource: name, ofType: "nib") != nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment