您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 基礎知識 >> iOS 基礎知識

iOS 基礎:UICollectionView 集合視圖入門

編輯:iOS 基礎知識

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 方法,也可動態調整行距、間距、區段內縮與項目尺寸。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved