Created
November 28, 2017 19:38
-
-
Save soxjke/e9860dacd61e0a2a63f1d81d731d0b13 to your computer and use it in GitHub Desktop.
NibInstantiatable
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 | |
| public protocol NibInstantiator { | |
| associatedtype Base | |
| func instantiate() -> Base | |
| } | |
| public extension NibInstantiator where Base: UIView { | |
| public func instantiate() -> Base { | |
| guard let view = | |
| UINib(nibName: String(describing: Base.self), bundle: Bundle(for: Base.self)) | |
| .instantiate(withOwner: nil, options: nil) | |
| .first as? Base else { fatalError("Can not load \(Base.self) from xib") } | |
| return view | |
| } | |
| } | |
| public struct NibInstantiatorType<T: UIView>: NibInstantiator { public typealias Base = T } | |
| public protocol NibInstantiatable { | |
| associatedtype T: UIView | |
| static var instantiator: NibInstantiatorType<T> { get } | |
| } | |
| public extension NibInstantiatable where Self: UIView { | |
| static var instantiator: NibInstantiatorType<Self> { return NibInstantiatorType<Self>() } | |
| } | |
| extension UITableView: NibInstantiatable {} | |
| extension UICollectionView: NibInstantiatable {} |
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 | |
| public protocol NibInstantiatable: class {} | |
| public extension UIView { | |
| public static func instantiate<T>() -> T | |
| where T: NibInstantiatable { | |
| guard let view = | |
| UINib(nibName: String(describing: T.self), bundle: Bundle(for: T.self)) | |
| .instantiate(withOwner: nil, options: nil) | |
| .first as? T else { fatalError("Can not load \(T.self) from xib") } | |
| return view | |
| } | |
| } | |
| extension UITableView: NibInstantiatable {} | |
| extension UICollectionView: NibInstantiatable {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment