1. 程式人生 > Android開發 >iOS 多section瀑布流實現(swift)

iOS 多section瀑布流實現(swift)

基於 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,section: Int) -> Int
  
  /// header高度(預設為0)
  @objc optional func referenceSizeForHeader(collectionView collection: UICollectionView,section: Int) -> CGSize
  
  /// footer高度(預設為0)
  @objc optional func referenceSizeForFooter(collectionView collection: UICollectionView,section: Int) -> CGSize
  
  /// 每個section 邊距(預設為0)
  @objc optional func insetForSection(collectionView collection: UICollectionView,section: Int) -> UIEdgeInsets
  
  /// 每個section item上下間距(預設為0)
  @objc optional func lineSpacing(collectionView collection: UICollectionView,section: Int) -> CGFloat
  
  /// 每個section item左右間距(預設為0)
  @objc optional func interitemSpacing(collectionView collection: UICollectionView,section: Int) -> CGFloat
  
  /// section頭部header與上個section尾部footer間距(預設為0)
  @objc optional func spacingWithLastSection(collectionView collection: UICollectionView,section: Int) -> CGFloat
複製程式碼

最後附上demo連結:github.com/RoganZheng/… 如果對你有幫助,記得點個 star。