Advertisement
ko7tya

Example

Feb 22nd, 2021
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.69 KB | None | 0 0
  1. struct MyModel: Equatable {
  2.     var id: Int
  3.     var showSomething: Bool
  4.     var someText: String
  5. }
  6.  
  7. class CellOne: UICollectionViewCell {}
  8. class CellTwo: UICollectionViewCell {}
  9.  
  10. class FooClass: UIViewController {
  11.     var collectionView: UICollectionView!
  12.     var dataSource: [MyModel] = []
  13.  
  14.     //Update your data source and reload collectionView
  15.     func updateData(with item: MyModel, for index: Int) {
  16.         var item = item
  17.         dataSource.enumerated().forEach {
  18.             if $0.element.id == item.id {
  19.                 item.showSomething.toggle()
  20.                 dataSource[$0.offset] = item
  21.                 collectionView.reloadData()
  22.             }
  23.         }
  24.     }
  25. }
  26.  
  27.  
  28.  
  29. extension FooClass: UICollectionViewDelegate {
  30.     func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  31.         //When some action triggered, update your dataSource and reload collectionview
  32.         let selectedItem = dataSource[indexPath.row]
  33.         updateData(with: selectedItem, for: indexPath.row)
  34.     }
  35. }
  36.  
  37. extension FooClass: UICollectionViewDataSource {
  38.     func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  39.         dataSource.count
  40.     }
  41.  
  42.     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  43.         let model = dataSource[indexPath.row]
  44.  
  45.         let cell: UICollectionViewCell
  46.  
  47.         if model.showSomething {
  48.             cell = CellOne()
  49.             //some logic update for cellOne
  50.         } else {
  51.             cell = CellTwo()
  52.             //some logic update for cellTwo
  53.         }
  54.         return cell
  55.     }
  56.  
  57.  
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement