在集合视图中,我想知道在集合视图中显示的第一个项目.我想我会看看visibleCells并且会成为列表中的第一个项目,但事实并非如此.
返回collectionView上可见的第一个项目:
UICollectionViewCell *cell = [self.collectionView.visibleCells firstObject];
Run Code Online (Sandbox Code Playgroud)
从collectionView中的所有项返回第一项
UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
Run Code Online (Sandbox Code Playgroud)
你不想要单元格,只需要数据:
NSIndexPath *indexPath = [[self.collectionView indexPathsForVisibleItems] firstObject];
id yourData = self.dataSource[indexPath.row];
Run Code Online (Sandbox Code Playgroud)
但visivleCells阵列没有订购!
那么,你需要订购它:
NSArray *indexPaths = [self.collectionView indexPathsForVisibleItems];
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"row" ascending:YES];
NSArray *orderedIndexPaths = [indexPaths sortedArrayUsingDescriptors:@[sort]];
// orderedIndexPaths[0] would return the position of the first cell.
// you can get a cell with it or the data from your dataSource by accessing .row
Run Code Online (Sandbox Code Playgroud)
编辑:我相信visibleCells(和类似)已经返回订单,但我没有在文档上找到任何相关的内容.所以我添加了订购部分只是为了确保.
Swift3
基于之前的答案,这里是Swift3等效于获取有序可见单元格,首先对可见索引路径进行排序,然后使用sorted和获取UICollectionViewCell flatMap.
let visibleCells = self.collectionView.indexPathsForVisibleItems
.sorted { left, right -> Bool in
return left.section < right.section || left.row < right.row
}.flatMap { indexPath -> UICollectionViewCell? in
return self.collectionView.cellForItem(at: indexPath)
}
Run Code Online (Sandbox Code Playgroud)
在更简化的版本中,可读性稍差
let visibleCells = self.collectionView.indexPathsForVisibleItems
.sorted { $0.section < $1.section || $0.row < $1.row }
.flatMap { self.collectionView.cellForItem(at: $0) }
Run Code Online (Sandbox Code Playgroud)