Get row count in UICollectionView

UICollection view automatically adjusts the number of rows based on the number of elements in each section and the size of each cell.

So, is there a way to get the number of rows in a UICollectionView?

For example: if I have a calendar with 31 days that automatically fits into n lines. How to get the value of this "n"?

+4
source share
1 answer

You can get the position of an element after placing it with [myCollectionView.collectionViewLayout layoutAttributesForItemAtIndexPath:]

, , Y- . , , .

:

NSInteger totalItems = [myCollectionView numberOfItemsInSection:0];
// How many items are there per row?
NSInteger currItem;
CGFloat currRowOriginY = CGFLOAT_MAX;
for (currItem = 0; currItem < totalItems; currItem++) {
    UICollectionViewLayoutAttributes *attributes = 
        [collectionView.collectionViewLayout layoutAttributesForItemAtIndexPath:
             [NSIndexPath indexPathForItem:currItem inSection:0]];

    if (currItem == 0) {
        currRowOriginY = attributes.frame.origin.y;
        continue;
    }

    if (attributes.frame.origin.y > currRowOriginY + 5.0f) {
        break;
    }
}
NSLog(@"new row started at item %ld", (long)currItem);
NSInteger totalRows = totalItems / currItem;
NSLog(@"%ld rows", (long)totalRows);

,

NSInteger totalItems = [self.timelineCollectionView numberOfItemsInSection:0];
NSIndexPath lastIndex = [NSIndexPath indexPathForItem:totalItems - 1 inSection:0];
UICollectionViewLayoutAttributes *attributes = 
    [myCollectionView.collectionViewLayout layoutAttributesForItemAtIndexPath:lastIndex];
// Frame of last item is now in attributes.frame

. . UICollectionViewFlowLayout.

UICollectionViewFlowLayout *myFlowLayout = (UICollectionViewFlowLayout*)myCollectionView.collectionViewFlowLayout;

myFlowLayout.headerReferenceSize
myFlowLayout.minimumLineSpacing

..

+4

Source: https://habr.com/ru/post/1538994/


All Articles