How do you determine spacing between cells in UICollectionView flowLayout

后端 未结 12 1218
夕颜
夕颜 2020-11-29 15:32

I have a UICollectionView with a flow layout and each cell is a square. How do I determine the spacing between each cells on each row? I can\'t seem to find the appropriate

12条回答
  •  心在旅途
    2020-11-29 16:05

    To get a maximum interitem spacing, subclass UICollectionViewFlowLayout and override layoutAttributesForElementsInRect: and layoutAttributesForItemAtIndexPath:.

    For example, a common problem is this: the rows of a collection view are right-and-left justified, except for the last line which is left-justified. Let's say we want all the lines to be left-justified, so that the space between them is, let's say, 10 points. Here's an easy way (in your UICollectionViewFlowLayout subclass):

    - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
        NSArray* arr = [super layoutAttributesForElementsInRect:rect];
        for (UICollectionViewLayoutAttributes* atts in arr) {
            if (nil == atts.representedElementKind) {
                NSIndexPath* ip = atts.indexPath;
                atts.frame = [self layoutAttributesForItemAtIndexPath:ip].frame;
            }
        }
        return arr;
    }
    
    - (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
        UICollectionViewLayoutAttributes* atts =
        [super layoutAttributesForItemAtIndexPath:indexPath];
    
        if (indexPath.item == 0) // degenerate case 1, first item of section
            return atts;
    
        NSIndexPath* ipPrev =
        [NSIndexPath indexPathForItem:indexPath.item-1 inSection:indexPath.section];
    
        CGRect fPrev = [self layoutAttributesForItemAtIndexPath:ipPrev].frame;
        CGFloat rightPrev = fPrev.origin.x + fPrev.size.width + 10;
        if (atts.frame.origin.x <= rightPrev) // degenerate case 2, first item of line
            return atts;
    
        CGRect f = atts.frame;
        f.origin.x = rightPrev;
        atts.frame = f;
        return atts;
    }
    

    The reason this is so easy is that we aren't really performing the heavy lifting of the layout; we are leveraging the layout work that UICollectionViewFlowLayout has already done for us. It has already decided how many items go in each line; we're just reading those lines and shoving the items together, if you see what I mean.

提交回复
热议问题