UICollection View 会根据每个部分的项目数和每个单元格的大小自动调整行数。
那么有没有办法获取 UICollectionView 中的行数?
例如:如果我有一个自动适合 n 行的 31 天日历。 我如何获得这个 'n' 的值?
最佳答案
您可以通过 [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
等等。
关于ios - 获取 UICollectionView 中的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23427778/