Skip to content

Instantly share code, notes, and snippets.

@Hadevs
Created May 21, 2020 16:22
Show Gist options
  • Save Hadevs/792b6694679297c1972e62129e5b9da6 to your computer and use it in GitHub Desktop.
Save Hadevs/792b6694679297c1972e62129e5b9da6 to your computer and use it in GitHub Desktop.
import UIKit
class CollectionViewCellWrapper<View: NibLoadable & UIView> {
static func register(in collectionView: UICollectionView) {
collectionView.register(WrappedCollectionViewCell<View>.self, forCellWithReuseIdentifier: View.name)
}
static func forceGet(from collectionView: UICollectionView, in indexPath: IndexPath) -> WrappedCollectionViewCell<View> {
let cell = collectionView.cellForItem(at: indexPath) as! WrappedCollectionViewCell<View>
return cell
}
static func get(from collectionView: UICollectionView, in indexPath: IndexPath) -> WrappedCollectionViewCell<View> {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: View.name, for: indexPath) as! WrappedCollectionViewCell<View>
return cell
}
}
@dynamicMemberLookup
class WrappedCollectionViewCell<View: NibLoadable & UIView>: UICollectionViewCell {
private(set) var view: View = View.loadFromNib()
subscript<T>(dynamicMember keyPath: KeyPath<View, T>) -> T {
return self.view[keyPath: keyPath]
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
let cell = self
cell.addSubview(view)
let constraints = ConstraintConstructor(subview: view).superViewCovered().constraints
cell.addConstraints(constraints)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment