-->

Rows and columns of UICollectionViewFlowLayout

2019-06-09 18:51发布

问题:

Given a UICollectionView with flow layout, what's the simplest way to calculate the number of columns (vertical direction) or rows (horizontal direction) of the collection view?

回答1:

My hackish way of doing it (assumes all elements have the same size):

- (void) countRowsAndColumns
{
    NSArray *layouts = [collectionViewLayout layoutAttributesForElementsInRect:self.collectionView.bounds];
    NSMutableSet *columns = [NSMutableSet set];
    NSMutableSet *rows = [NSMutableSet set];
    for (UICollectionViewLayoutAttributes *layout in layouts)
    {
        if (layout.representedElementCategory != UICollectionElementCategoryCell) continue;
        CGFloat x = layout.frame.origin.x;
        [columns addObject:@(x)];
        CGFloat y = layout.frame.origin.y;
        [rows addObject:@(y)];
    }
    _columnCount = columns.count;
    _rowCount = rows.count;
}