Search code examples
iosxcodeuicollectionviewnsindexpath

getting index on NSIndexPath on UICollectionView


I have an array of items for UICollectionView(with 2 columns and 3 rows) and I want to access it with the indexPath but I cant made it

If I use indexPath.row or indexPath.item I get 0,1,0,1,0,1.

If I use indexPath.section I get 0,0,1,1,2,2

What I want is 0,1,2,3,4,5,6

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

MenuCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
//cell.backgroundColor = [UIColor redColor ];
cell.backgroundColor = [UIColor whiteColor ];

UIImage* imagenprobar =[UIImage imageNamed: [imagenes objectAtIndex: indexPath.item]];
[cell.imagen setImage: imagenprobar];




cell.label.text = [textos objectAtIndex: indexPath.item];

return cell;

}


Solution

  • Use (indexpath.section*yourTotalColumn)+indexPath.row to calculate exact index of array for UICollectionView.

    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
    {
       ......................
    
       .......................
    
       //Now calculate index of array (datasource) Note : here column is 2.
       NSInteger index = (indexpath.section*2)+indexPath.row
       cell.label.text = [textos objectAtIndex:index];
    
       return cell;
    

    }