UICollection视图会根据每个部分的项目数和每个单元格的大小自动调整行数。
那么有没有办法获取UICollectionView中的行数?
例如:如果我有一个31天的日历,自动适合n行。 如何获得这个' n'的价值? ?
答案 0 :(得分:4)
您可以使用[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);
如果您 知道商品的尺寸,您可以使用
获取 last 项目的位置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
等等。