Search code examples
iosuicollectionviewuicollectionviewlayout

Change the sequence of uicollectionviewcell


I am trying to change the sequence to cells rendered in collectionview. By default in vertical layout collectionview cells are displayed in

1 2 3
4 5 6
7 8 9

What i am trying to do is change this sequence in following ways

1  2  3
6  5  4      <----- this order is reversed
7  8  9
12 11 10     <----- this order is reversed

Can any one tell me how do i achieve this kind of behaviour.

So far i have implemented UICollectionViewFlowLayout and trying to manipulate its methods but got no success

Note: All items must be loaded in one section only


Solution

  • I found the solution by inheriting UICollectionViewLayout and calculated the desired frame for each item. in prepareLayout method.

    Still there are scope for improvement in below code.

    -(void)prepareLayout{
        NSInteger itemCount = [self.collectionView numberOfItemsInSection:0];
        NSMutableDictionary *layoutAttr = [NSMutableDictionary dictionary];
        CGFloat y=0,x=0;
        for (int i = 0; i<itemCount; i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
            CGRect frame;
            if (indexPath.row == 0) {
                x= 0;
                y=0;
                frame = CGRectMake(x,  y, self.itemSize.width, self.itemSize.height);
                x += self.itemSize.width;
            }else if (indexPath.row % 2 == 0 ) {
                y += self.itemSize.height;
                x -=self.itemSize.width;
                frame = CGRectMake(x,  y, self.itemSize.width, self.itemSize.height);
                if (x <= 0) {
                    x += self.itemSize.width;
                }else{
                    x -= self.itemSize.width;
                }
            }else{
                frame = CGRectMake(x,  y, self.itemSize.width, self.itemSize.height);
                x += self.itemSize.width;
            }
            attributes.frame=frame;
    
            attributes.zIndex = i;
            layoutAttr[indexPath] = attributes;
        }
        layoutAttributes=layoutAttr;
    }