iOS 多section瀑布流实现(swift)

5,580 阅读1分钟

基于 UICollectionViewFlowLayout,实现一个支持多 section 的瀑布流组件

 最近因项目需求,写了一个支持多 section 的瀑布流实现组件,完全基于 swift 5 来实现。 先来直接看效果图:

 (PS:瀑布流的实现原理其实挺简单的,网上现有的教程一抓一大把,我也懒得复述了。。。)

稍微整理了下,让这个小组件尽量做到集成简单快捷。

1. 初始化

 因为基于 UICollectionViewFlowLayout 实现的,所以该 flowLayout 的初始化调用流程与系统的无异,只需要遵循 WaterfallMutiSectionDelegate 代理。

let layout = WaterfallMutiSectionFlowLayout()
layout.delegate = self
let collection = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)

2. 代理实现

2.1 必须实现代理方法

/// collectionItem高度
func heightForRowAtIndexPath(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, indexPath: IndexPath, itemWidth: CGFloat) -> CGFloat

2.2 可选实现代理方法

  /// 每个section 列数(默认2列)
  @objc optional func columnNumber(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> Int
  
  /// header高度(默认为0)
  @objc optional func referenceSizeForHeader(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGSize
  
  /// footer高度(默认为0)
  @objc optional func referenceSizeForFooter(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGSize
  
  /// 每个section 边距(默认为0)
  @objc optional func insetForSection(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> UIEdgeInsets
  
  /// 每个section item上下间距(默认为0)
  @objc optional func lineSpacing(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGFloat
  
  /// 每个section item左右间距(默认为0)
  @objc optional func interitemSpacing(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGFloat
  
  /// section头部header与上个section尾部footer间距(默认为0)
  @objc optional func spacingWithLastSection(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGFloat

最后附上demo链接:github.com/RoganZheng/… 如果对你有帮助,记得点个 star。