Search code examples
iosios7uicollectionviewuicollectionviewlayout

UICollectionView scroll horizontal with data flowing from left to right


I saw a somewhat similar problem here: Reorder cells of UICollectionView. However, the solution involves overriding UICollectionViewFlowLayout to reorder the cells. But in my case, I don't want to reorder the cells, but simply transform the datasource accordingly.

I am creating a UICollectionView that scrolls horizontally. By default, the items are ordered from top to bottom:

cell1  cell4  cell7  cell10
cell2  cell5  cell8  cell11
cell3  cell6  cell9  cell12

I am fine with the physical flow of cells. But however, I want my data to flow from left to right:

data1  data2  data3  data4 
data5  data6  data7  data8 
data9  data10 data11 data12

Simply using indexPath.item to figure out which data to use will not work. I have to somehow "transform" the index. For example, to display contents for cell2, I need to use data5, and not data2.

Something along the lines of:

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

   NSInteger index = //Use proper index based on transformed indexPath.item, instead of just indexPath.item
   NSDate *cellDate = [self.dateArray objectAtIndex:index]
   ...
}

Any ideas on how to make that transformation?


Solution

  • Figure out how to do it:

     -(NSDate*)cellDateBasedOnIndexPath:(NSIndexPath*)indexPath {
         NSInteger row = indexPath.item % NUMBER_OF_ROWS + 1;
         NSInteger column = indexPath.item/NUMBER_OF_ROWS + 1;
         NSInteger itemIndex = row * NUMBER_OF_COLUMNS - (NUMBER_OF_COLUMNS - column) - 1;
    
         //Use itemIndex to index through the data source...
    
     }