UICollectionView - 資料來源

每個集合檢視都必須包含 Datasource 物件。Datasource 物件是你的應用在 UICollectionView 中顯示的內容。所有 Datasource 物件必須至少實現 collectionView:numberOfItemsInSection:collectionView:cellForItemAtIndexPath:方法。

所需方法

迅速

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // Return how many items in section
    let sectionArray = _data[section]
    return sectionArray.count
}
    
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

   let cell = collectionView.dequeueReusableCellWithReuseIdentifier(MyCellID) 
   // If you use a custom cell class then cast the cell returned, like:
   // as! MyCollectionViewCellClass
   // or you will have errors when you try to use features of that class.

   //Customize your cell here, default UICollectionViewCells do not contain any inherent
   //text or image views (like UITableView), but some could be added, 
   //or a custom UICollectionViewCell sub-class could be used
   return cell
}

目標 C.

- (NSInteger)collectionView:(UICollectionView*)collectionView numberOfItemsInSection:(NSInteger)section {
    // Return how many items in section
    NSArray *sectionArray = [_data objectAtIndex:section];
    return [sectionArray count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath {
   // Return a cell
   UICollectionViewCell *newCell = [self.collectionView 
                                       dequeueReusableCellWithReuseIdentifier:MyCellID                                                                             
                                                                 forIndexPath:indexPath];
   //Customize your cell here, default UICollectionViewCells do not contain any inherent
   //text or image views (like UITableView), but some could be added, 
   //or a custom UICollectionViewCell sub-class could be used
   return newCell;
}