Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NibInstantiatable
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 {}
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
You can’t perform that action at this time.