UICollectionView horizontal paging - can I use Flow Layout?

后端 未结 8 2101
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-07 09:27

This is related to but distinct from To use Flow Layout, or to Customize?.

Here is an illustration of what I’m trying to do:

8条回答
  •  醉酒成梦
    2020-12-07 09:48

    @interface HorizontalCollectionViewLayout : UICollectionViewFlowLayout
    
    @end
    
    @implementation HorizontalCollectionViewLayout
    
    - (instancetype)init
    {
        self = [super init];
        if (self) {
            self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
            self.minimumLineSpacing = 0;
            self.minimumInteritemSpacing = 0;
        }
        return self;
    }
    
    - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
    {
        NSArray *attributesArray = [super layoutAttributesForElementsInRect:rect];
    
        NSInteger verticalItemsCount = (NSInteger)floorf(self.collectionView.bounds.size.height / self.itemSize.height);
        NSInteger horizontalItemsCount = (NSInteger)floorf(self.collectionView.bounds.size.width / self.itemSize.width);
        NSInteger itemsPerPage = verticalItemsCount * horizontalItemsCount;
    
        for (NSInteger i = 0; i < attributesArray.count; i++) {
            UICollectionViewLayoutAttributes *attributes = attributesArray[i];
            NSInteger currentPage = (NSInteger)floor((double)i / (double)itemsPerPage);
            NSInteger currentRow = (NSInteger)floor((double)(i - currentPage * itemsPerPage) / (double)horizontalItemsCount);
            NSInteger currentColumn = i % horizontalItemsCount;
            CGRect frame = attributes.frame;
            frame.origin.x = self.itemSize.width * currentColumn + currentPage * self.collectionView.bounds.size.width;
            frame.origin.y = self.itemSize.height * currentRow;
            attributes.frame = frame;
        }
        return attributesArray;
    }
    
    - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
    {
        return YES;
    }
    
    @end
    

提交回复
热议问题