iOS UICollectionView UICollectionView - Datasource


Example

Every collection view must have a Datasource object. The Datasource object is the content that your app will display within the UICollectionView. At a minimum, all Datasource objects must implement the collectionView:numberOfItemsInSection: and collectionView:cellForItemAtIndexPath: methods.

Required Methods

Swift

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
}

Objective 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;
}