Created
October 9, 2015 21:08
-
-
Save joshavant/86df569f054c07921f60 to your computer and use it in GitHub Desktop.
NibLoadableView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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