IGListKit

本文学习自IGListKit Tutorial: Better UICollectionViews

IGListKit是一个数据驱动UICollectionView框架,使用此框架提供对象数组显示在UICollectionView中。对于每种类型的对象,Adapter创建Section controller,其中包含创建cell的所有详细信息


IGListKit会自动比较对象数据,并在其发生变化时执行UICollectionView的更新动画,而不需要自己实现batch updating

使用IGListKit

1.视图

IGListKit中,仍然使用UICollectionView以及UICollectionViewFlowLayout来初始化列表容器

2. 数据源

在UICollectionView,通过UICollectionViewDataSource代理提供数据源
在IGListKit中,使用ListAdapter控制colletionView,实现ListAdapterDataSource协议作为数据源,此时不是提供cell以及的数量,而是返回一组section controllers

lazy var adapter: ListAdapter = {
  return ListAdapter(
  updater: ListAdapterUpdater(),
  viewController: self, 
  workingRangeSize: 0)
}()
  • updater: 继承自ListUpdatingDelegate协议,处理row和section的更新。ListAdapterUpdater提供了一个默认的实现
  • viewController: 容纳adapter的控制器
  • workingRangeSize: 工作范围size。使用这个参数允许为可见范围外的section准备内容
adapter.collectionView = collectionView
adapter.dataSource = self

将adapter和collectionView绑定,并设置数据源datasource为self,因此需要继承实现ListAdapterDataSource协议

objects(for:) // 返回要在collectionView上展示的一组数据

listAdapter(_:sectionControllerFor:) //为每个数据对象 返回一份section controller.

emptyView(for:) //当list是空的时候 展示的视图

Section Controller

Section Controller是一种抽象,用于给定数据对象,配置和控制collectionView的section中的cells。类似于针对View的View-Model
因此,为了区分不同类型的数据和行为,需要创建新的SectionController

class JournalSectionController: ListSectionController {
    override func numberOfItems() -> Int {
        return 2
    }
    
    override func sizeForItem(at index: Int) -> CGSize {
        .zero
    }
    
    override func cellForItem(at index: Int) -> UICollectionViewCell {
        let cell = collectionContext?.dequeueReusableCell(of: cellClass, for: self, at: index)
        return cell
    }
    
    override func didUpdate(to object: Any) {
        entry = object as? JournalEntry
    }
    
    override func didSelectItem(at index: Int) {
  collectionContext?.performBatch(animated: true, updates: { batchContext in
    self.expanded.toggle()
    batchContext.reload(self)
  }, completion: nil)
}
}

didUpdate(to object: Any): IGListKit在将对象交给section controller之前调用。该方法在所有所有其他协议方法之前调用,可以用来保存传递进来的对象

cellForItem(at index: Int)类似collectionView中的cellForItem,在其中复用cell

ListCollectionContext:是带有adapter信息的上下文对象,collectionView和ViewController信息

didSelectItem: 当进行点击事件时调用该方法

performBatch(animated:updates:completion:)在一个transaction中执行批量更新,可以无论在何时当该sectionController中cell的内容或者数量改变时,调用其进行更新。

更新

也可以通过adaper进行更新

adapter.performUpdates(animated: true, completion: nil)

通过该方法使ListAdapter使其datasource更新数据源,询问新的对象。来更新、移动、插入对象

参考资料

https://www.jianshu.com/p/3517619085f7

https://instagram.github.io/IGListKit/getting-started.html

https://juejin.im/entry/5bee4514e51d4556a633c6c9