ios - 获取 UICollectionView 中的行数

标签 ios ios6 uicollectionview

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/

相关文章:

ios - 调用 .cancel() 时 DispatchWorkItem 不终止函数

iphone - 所有 View 中的 Ios 音频播放器

iphone - 如何设计 iPhone 4s 和 iPhone 5 的 View ?

javascript - IOS 9 正在阻止模态移动链接

ios - 如何使用模型类初始化 Core Data ManagedObjectContext?

ios - 缩放 CALayer 会使 View 变得模糊

ios - UICollectionViewCell : can I know exactly when the cell appears and disappears?

ios - Swift - 如何在 UICollectionView 中扩展单元格

ios - UICollectionView 单元格对齐方式

java - 将文本数据存储在一个/多个文件中以使其可用于各种平台的最佳方法是什么?