之前一直覺得Instagram的iOS APP首頁的流暢度非常不錯。現(xiàn)在他們開源了這個IGListKit框架现横,總要好好研究研究奋构。
核心架構(gòu)比較清晰。每一個條目就是一種sectionController(如圖黃色框內(nèi))晌该。每個section對應(yīng)一個Item肥荔。具體結(jié)構(gòu)如下
框架的文檔很詳細但是是英文版的绿渣。
# Latest release of IGListKit
pod 'IGListKit', '~> 2.0.0'
# Use the master branch (we use this at Instagram)
pod 'IGListKit', :git => 'https://github.com/Instagram/IGListKit.git', :branch => 'master'
使用很簡單。新建ViewController和someSectionController 繼承
IGListSectionController并遵守IGListSectionType次企。
viewController中設(shè)置UI
let layout = UICollectionViewFlowLayout()
let collectionView = IGListCollectionView(frame: .zero, collectionViewLayout: layout)
let updater = IGListAdapterUpdater()
let adapter = IGListAdapter(updater: updater, viewController: self, workingRangeSize: 0)
//set方法調(diào)用數(shù)據(jù)源更新操作 把objects(for listAdapter: IGListAdapter) -> [IGListDiffable] 方法設(shè)置的數(shù)據(jù)傳給cectionController
adapter.collectionView = collectionView
接下來設(shè)置數(shù)據(jù)怯晕,根據(jù)預(yù)先分好的組。
func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] {
// this can be anything!
return [ "Foo", "Bar", 42, "Biz" ]
}
func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController {
//根據(jù)需求返回不同的sectionController
return someSectionController()
}
//沒有數(shù)據(jù)時缸棵,顯示的自定義view
func emptyView(for listAdapter: IGListAdapter) -> UIView? {
return nil
}
- (void)updateBackgroundViewWithItemCount:(NSUInteger)itemCount {
UIView *backgroundView = [self.dataSource emptyViewForListAdapter:self];
// don't do anything if the client is using the same view
if (backgroundView != _collectionView.backgroundView) {
// collection view will just stack the background views underneath each other if we do not remove the previous
// one first. also fine if it is nil
[_collectionView.backgroundView removeFromSuperview];
_collectionView.backgroundView = backgroundView;
}
_collectionView.backgroundView.hidden = itemCount > 0;
}
//someSectionController中設(shè)置數(shù)據(jù)
func numberOfItems() -> Int {
return 4
}
//section中每一行高
func sizeForItem(at index: Int) -> CGSize {
return CGSize(width: collectionContext!.containerSize.width, height: 105)
}
//collectionContext屬性 獲取到objects(for listAdapter: IGListAdapter) -> [IGListDiffable] 中設(shè)置的data
func cellForItem(at index: Int) -> UICollectionViewCell {
let cell = collectionContext!.dequeueReusableCell(of: LabelCell.self, for: self, at: index) as! LabelCell
let section = collectionContext!.section(for: self)
cell.label.text = "Section \(section), cell \(index)"
return cell
}
func didUpdate(to object: Any) {}
func didSelectItem(at index: Int) {}