Last active
January 25, 2016 12:48
-
-
Save werediver/8f3e55babf651cfc0251 to your computer and use it in GitHub Desktop.
This file contains 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 | |
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