Skip to content

Instantly share code, notes, and snippets.

@joshavant
Created October 9, 2015 21:08
Show Gist options
  • Select an option

  • Save joshavant/86df569f054c07921f60 to your computer and use it in GitHub Desktop.

Select an option

Save joshavant/86df569f054c07921f60 to your computer and use it in GitHub Desktop.
NibLoadableView
import UIKit
protocol NibLoadable {
func setupFromXib()
}
// This extension loads a .xib file with the same filename as the class name
// i.e. `class FoobarHeaderView` -> loads FoobarHeaderView.xib
extension NibLoadable where Self: UIView {
func setupFromXib() {
// load the root UIView (i.e. root subview layer of the xib)
let bundle = NSBundle(forClass: self.dynamicType)
let className = NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last!
let nib = UINib(nibName: className, bundle: bundle)
// reminder: instantiating with `owner: self` takes care of hooking up
// all the IBOutlets from the nib, to this class
let rootView = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
// setup that view's geometry
rootView.frame = bounds
rootView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
// add that view to myself
addSubview(rootView)
}
}
import UIKit
// Subclasses:
// When reimplementing `commonInit`, call the super implementation, first.
class NibLoadableView: UIView, NibLoadable {
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
setupFromXib()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment