UICollectionView 是 iOS 6 之後加入的集合視圖,常用於建立網格、瀑布流或自訂排版。它與 UITableView 類似,都需要 dataSource 與 delegate,但多了 layout 物件來決定排列方式。
先建立 UICollectionViewFlowLayout,設定 scrollDirection、itemSize、sectionInset 等。接著建立 UICollectionView,指定 layout,並設定 dataSource 與 delegate。
若要顯示 cell,必須註冊 cell;若要顯示區段頭尾視圖,則需註冊 supplementary view。
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; layout.scrollDirection = UICollectionViewScrollDirectionVertical; UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:[[UIScreen mainScreen] bounds] collectionViewLayout:layout]; collectionView.dataSource = self; collectionView.delegate = self; [collectionView registerClass:[YourCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
資料源需回傳每個 section 的項目數量,並提供 cell。若使用自訂 cell,可在 cellForItemAtIndexPath 中設定內容。
若需要 header 或 footer,可實作 viewForSupplementaryElementOfKind:atIndexPath:,並回傳對應的 UICollectionReusableView。
delegate 則可處理選取事件,例如 didSelectItemAtIndexPath:。透過 layout 的 delegate 方法,也可動態調整行距、間距、區段內縮與項目尺寸。