cdub cdub - 12 days ago 6
iOS Question

How do I add a counter to a cell in UICollectionView cells?

I have the following code:

- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

cell.backgroundColor = [UIColor whiteColor];

return cell;
}


How do I add a counter to dispaly in my cell that shows the number of the cell in the order it was created? Like cell 1 would say 1, 2 is 2, and so on.

Answer

Create a subclass of UICollectionViewCell. Add the counter (maybe just a label?) in the init method of the cell. Register you class for a cell identifier of your wish

[self.collectionView registerClass:[MyCollectionViewCell class] 
        forCellWithReuseIdentifier:@"myCellIdentifier"];

and dequeue the cell with the identifier. Then set the label value.

- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCellIdentifier" forIndexPath:indexPath];

    cell.backgroundColor = [UIColor whiteColor];
    cell.counterLabel.text = [NSString stringWithFormat:@"%d", indexPath.row];

    return cell;
}