Cell spacing in UICollectionView

后端 未结 26 3283
旧巷少年郎
旧巷少年郎 2020-11-22 15:53

How do I set cell spacing in a section of UICollectionView? I know there is a property minimumInteritemSpacing I have set it to 5.0 still the spaci

26条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 16:20

    I have problem with the accepted answer, so I updated it, this is working for me:

    .h

    @interface MaxSpacingCollectionViewFlowLayout : UICollectionViewFlowLayout
    @property (nonatomic,assign) CGFloat maxCellSpacing;
    @end
    

    .m

    @implementation MaxSpacingCollectionViewFlowLayout
    
    - (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect {
        NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
    
        if (attributes.count <= 0) return attributes;
    
        CGFloat firstCellOriginX = ((UICollectionViewLayoutAttributes *)attributes[0]).frame.origin.x;
    
        for(int i = 1; i < attributes.count; i++) {
            UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[i];
            if (currentLayoutAttributes.frame.origin.x == firstCellOriginX) { // The first cell of a new row
                continue;
            }
    
            UICollectionViewLayoutAttributes *prevLayoutAttributes = attributes[i - 1];
            CGFloat prevOriginMaxX = CGRectGetMaxX(prevLayoutAttributes.frame);
            if ((currentLayoutAttributes.frame.origin.x - prevOriginMaxX) > self.maxCellSpacing) {
                CGRect frame = currentLayoutAttributes.frame;
                frame.origin.x = prevOriginMaxX + self.maxCellSpacing;
                currentLayoutAttributes.frame = frame;
            }
        }
        return attributes;
    }
    
    @end
    

提交回复
热议问题