Skip to content

Instantly share code, notes, and snippets.

@werediver
Last active January 25, 2016 12:48
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 werediver/8f3e55babf651cfc0251 to your computer and use it in GitHub Desktop.
Save werediver/8f3e55babf651cfc0251 to your computer and use it in GitHub Desktop.
import UIKit
import PureLayout
extension UINib {
func instantiateWithOwner<T: AnyObject>(owner: AnyObject?, options: [NSObject : AnyObject]? = nil, type: T.Type) -> T {
let objs = self.instantiateWithOwner(owner, options: options)
return objs.findFirst { $0 is T } as! T
}
}
protocol HasNib: AnyObject {
static var nib: UINib { get }
}
extension HasNib {
static var nib: UINib {
return UINib(nibName: typeName(Self), bundle: NSBundle(forClass: Self.self))
}
}
// MARK: - NibObject
protocol NibObject: HasNib {
static func loadFromNib(owner: AnyObject?) -> Self
}
extension NibObject {
static func loadFromNib(owner: AnyObject? = nil) -> Self {
return nib.instantiateWithOwner(owner, type: Self.self)
}
}
// MARK: - NibOwner
protocol NibOwner: HasNib {
typealias NibContentClass
func loadContentFromNib()
func installContent(content: NibContentClass) // Template method.
}
extension NibOwner where NibContentClass: AnyObject {
/**
* The typical usage would be as follows.
*
* override init(frame: CGRect) {
* super.init(frame: frame)
* loadContentFromNib()
* }
*
* required init?(coder decoder: NSCoder) {
* super.init(coder: decoder)
* loadContentFromNib()
* }
*/
func loadContentFromNib() {
let content = Self.nib.instantiateWithOwner(self, options: nil, type: NibContentClass.self)
installContent(content)
}
}
extension NibOwner where Self: UIView, NibContentClass: UIView {
func installContent(content: NibContentClass) {
addSubview(content)
content.autoPinEdgesToSuperviewEdges()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment