How can I center rows in UICollectionView?

前端 未结 9 1614
囚心锁ツ
囚心锁ツ 2021-02-02 06:24

I have a UICollectionView with random cells. Is there any method that allows me to center rows?

This is how it looks by default:

[ x x x x         


        
9条回答
  •  佛祖请我去吃肉
    2021-02-02 07:08

    I've subclassed UICollectionViewFlowLayout - altered the code i've found here for left aligned collection view.

    1. Left align the collection view
    2. Group the attributes for line arrays
    3. For each line:
      • calculate the space on the right side
      • add half of the the space for each attribute of the line

    It's looks like this:

    - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    
        NSArray *attributesForElementsInRect = [super layoutAttributesForElementsInRect:rect];
        NSMutableArray *newAttributesForElementsInRect = [[NSMutableArray alloc] initWithCapacity:attributesForElementsInRect.count];
    
        CGFloat leftMargin = self.sectionInset.left;
        NSMutableArray *lines = [NSMutableArray array];
        NSMutableArray *currLine = [NSMutableArray array];
    
        for (UICollectionViewLayoutAttributes *attributes in attributesForElementsInRect) {
            // Handle new line
            BOOL newLine = attributes.frame.origin.x <= leftMargin;
            if (newLine) {
                leftMargin = self.sectionInset.left; //will add outside loop
                currLine = [NSMutableArray arrayWithObject:attributes];
            } else {
                [currLine addObject:attributes];
            }
    
            if ([lines indexOfObject:currLine] == NSNotFound) {
                [lines addObject:currLine];
            }
    
            // Align to the left
            CGRect newLeftAlignedFrame = attributes.frame;
            newLeftAlignedFrame.origin.x = leftMargin;
            attributes.frame = newLeftAlignedFrame;
    
            leftMargin += attributes.frame.size.width + self.minimumInteritemSpacing;
            [newAttributesForElementsInRect addObject:attributes];
        }
    
        // Center left aligned lines
        for (NSArray *line in lines) {
            UICollectionViewLayoutAttributes *lastAttributes = line.lastObject;
            CGFloat space = CGRectGetWidth(self.collectionView.frame) - CGRectGetMaxX(lastAttributes.frame);
    
            for (UICollectionViewLayoutAttributes *attributes in line) {
                CGRect newFrame = attributes.frame;
                newFrame.origin.x = newFrame.origin.x + space / 2;
                attributes.frame = newFrame;
    
            }
        }
    
        return newAttributesForElementsInRect;
    }
    

    Hope it helps someone :)

提交回复
热议问题