How can I center rows in UICollectionView?

前端 未结 9 1712
囚心锁ツ
囚心锁ツ 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:18

    In case anyone has a CollectionView that has 2 columns, and if number of items is odd, the last item should be center aligned. Then use this

    DNLastItemCenteredLayout

    - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
        NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
    
        for (UICollectionViewLayoutAttributes *attribute in attributes) {
            NSInteger itemCount = [self.collectionView.dataSource collectionView:self.collectionView
                                                          numberOfItemsInSection:attribute.indexPath.section];
            if (itemCount % 2 == 1 && attribute.indexPath.item == itemCount - 1) {
                CGRect originalFrame = attribute.frame;
                attribute.frame = CGRectMake(self.collectionView.bounds.size.width/2-originalFrame.size.width/2,
                                             originalFrame.origin.y,
                                             originalFrame.size.width,
                                             originalFrame.size.height);
            }
        }
    
        return attributes;
    }
    

提交回复
热议问题