UICollectionView 是可高度自訂的集合視圖,常用於建立網格、瀑布流、輪播與自定義版面。它與 UITableView 相似,但透過 Layout 物件決定內容排列方式。
Cell 是內容主體,可重複使用;Supplementary Views 可作為 header 或 footer;Decoration Views 則是背景裝飾。三者都由 UICollectionViewLayout 決定位置與樣式。
UICollectionViewDataSource 負責提供 section 數量、item 數量與 cell 內容。UICollectionViewDelegate 處理選取、高亮與互動行為。UICollectionViewDelegateFlowLayout 則可調整間距、尺寸與 section 內縮邊距。
UICollectionViewFlowLayout 是 UIKit 內建的線性排列方式,可設定滾動方向、項目大小、行距、列距與 header footer 尺寸。若需求較簡單,通常可直接使用。
若需要更複雜版面,可自訂 UICollectionViewLayout。實作時通常需回傳內容尺寸、指定範圍內的布局屬性,以及 indexPath 對應的屬性。prepareLayout 可用於初始化參數,shouldInvalidateLayoutForBoundsChange 則決定滾動時是否重新計算。
理解 UICollectionView 的關鍵,是把資料、互動與版面配置分開思考。先掌握內建 FlowLayout,再進一步自訂 Layout,就能處理大多數複雜列表場景。