Advertisement
Guest User

CollectionDataSource

a guest
Oct 18th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.64 KB | None | 0 0
  1. open class CollectionDataSource<Provider: CollectionDataProviderProtocol, Cell: UICollectionViewCell>: NSObject, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout where Cell: ConfigurableCell, Provider.T == Cell.T {
  2.  
  3.   // MARK: - Private Properties
  4.   let provider: Provider
  5.   let collectionView: UICollectionView
  6.  
  7.   // Initialize and setup CollectionDataSource
  8.   // CollectionDataSource sets itself as the delegate for UICollectionViewDataSource and UICollectionViewDelegate
  9.   init(collectionView: UICollectionView, provider: Provider) {
  10.     self.collectionView = collectionView
  11.     self.provider = provider
  12.     super.init()
  13.     setup()
  14.   }
  15.  
  16.   func setup(){
  17.     collectionView.dataSource = self
  18.     collectionView.delegate = self
  19.   }
  20.  
  21.   public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  22.     return provider.numberOfItems(in: section)
  23.   }
  24.  
  25.   public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  26.     return CGSize(width: collectionView.frame.width / 2 - 20, height: 250)
  27.   }
  28.  
  29.   public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  30.     guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Cell.reuseIdentifier, for: indexPath) as? Cell else {
  31.       return UICollectionViewCell()
  32.     }
  33.    
  34.     let item = provider.item(at: indexPath)
  35.     if let item = item {
  36.       cell.configure(item, at: indexPath)
  37.     }
  38.    
  39.     return cell
  40.   }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement