Rows and columns of UICollectionViewFlowLayout

2019-06-09 18:56发布

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条回答
时光不老,我们不散
2楼-- · 2019-06-09 19:40

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;
}
查看更多
登录 后发表回答