10

On a collection view, i would like to know the first item that's being displayed on the collection view. I figured I would look at visibleCells and would be the first item on the list, but it's not the case.

3
  • 1
    do you want to see first item in collection view or you want to see first item in your visible cells in collection view? Commented Jun 12, 2015 at 20:06
  • You can use "- (NSArray *)indexPathsForVisibleItems" method to view first item if any visible cells are there in collection view. Commented Jun 12, 2015 at 20:08
  • first as in the top most cell that is showing on screen.
    – Frank
    Commented Jun 12, 2015 at 20:10

5 Answers 5

13

Updated for Swift5

let visibleCells = self.collectionView.indexPathsForVisibleItems
        .sorted { left, right -> Bool in
            return left.section < right.section || (left.section == right.section && left.row < right.row)
        }
        .compactMap { [weak self] in indexPath -> UICollectionViewCell? in
            return self?.collectionView.cellForItem(at: indexPath)
        }

Please note that any self in closure could keep a strong reference if not weaken.

let visibleCells = self.collectionView.indexPathsForVisibleItems
        .sorted { $0.section < $1.section || ($0.section == $1.section && $0.row < $1.row) }
        .flatMap { [weak self] in self?.collectionView.cellForItem(at: $0) }

Swift3

Based on previous answer, here is a Swift3 equivalent to get ordered visible cells, first ordering visible indexpath, then fetching UICollectionViewCell using sorted and flatMap.

let visibleCells = self.collectionView.indexPathsForVisibleItems
    .sorted { left, right -> Bool in
        return left.section < right.section || (left.section == right.section && left.row < right.row)
    }.flatMap { [weak self] in indexPath -> UICollectionViewCell? in
        return self?.collectionView.cellForItem(at: indexPath)
    }

In an even more simplified version, a bit less readable

let visibleCells = self.collectionView.indexPathsForVisibleItems
    .sorted { $0.section < $1.section || ($0.section == $1.section && $0.row < $1.row) }
    .flatMap { [weak self] in self?.collectionView.cellForItem(at: $0) }
2
  • 2
    Seem like just .sorted() will give you the "expected" default ascending sort order. Commented May 30, 2018 at 11:56
  • non-escaping closures (like compactMap) are executed in scope (immediately), so there's no [weak self] requirement.
    – joe
    Commented Nov 24, 2022 at 17:46
10

Returning the first item visible on the collectionView:

UICollectionViewCell *cell = [self.collectionView.visibleCells firstObject];

returning the first item from all the items in the collectionView

UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];

You don't want the cell, just the data:

NSIndexPath *indexPath = [[self.collectionView indexPathsForVisibleItems] firstObject];
id yourData = self.dataSource[indexPath.row];

But the visivleCells array is not ordered!!

Well, then you need to order it:

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

Edit: i do believe the visibleCells (and the like) return ordered already, but i didn't find anything regarding this on the docs. so i added the ordering part just to make sure.

4
  • i just tried this but it seems like the array would have the first item as a buffer of some sort. the second item is the first one that's displayed.
    – Frank
    Commented Jun 12, 2015 at 20:26
  • This is weird. try doing this again, but dont scroll down the table/ just let the first item visible, get the first visible item, and then get the first cell by hand (with NSIndexPath), see if they are the same. Technically, this code should work, i suggest you post some code :)
    – Erakk
    Commented Jun 12, 2015 at 20:30
  • 3
    I have seen the array of visibleCells be unordered, so this is a good idea.
    – erikprice
    Commented May 17, 2017 at 18:54
  • Yes,the array of visibleCells is unordered.
    – SSS
    Commented May 3, 2019 at 8:43
1

Here's my take on it, added as a category on UICollectionViewCell.

@implementation UICollectionView (LTSortedCells)

-(NSArray<UICollectionViewCell*>*)LT_visibleCellsSortedByIndexPath
{
    NSMutableDictionary<NSIndexPath*,UICollectionViewCell*>* dict = [NSMutableDictionary dictionary];
    NSArray<NSIndexPath*>* indexPaths = self.indexPathsForVisibleItems;
    NSArray<UICollectionViewCell*>* cells = self.visibleCells;
    [indexPaths enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull indexPath, NSUInteger idx, BOOL * _Nonnull stop) {
        UICollectionViewCell* cellForIndexPath = [cells objectAtIndex:idx];
        [dict setObject:cellForIndexPath forKey:indexPath];
    }];
    NSArray<NSIndexPath*>* sortedIndexPaths = [indexPaths sortedArrayUsingComparator:^NSComparisonResult(NSIndexPath* _Nonnull ip1, NSIndexPath* _Nonnull ip2) {
        return [ip1 compare:ip2];
    }];
    NSMutableArray<UICollectionViewCell*>* sortedCells = [NSMutableArray array];
    [sortedIndexPaths enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull indexPath, NSUInteger idx, BOOL * _Nonnull stop) {
        UICollectionViewCell* cellForIndexPath = [dict objectForKey:indexPath];
        [sortedCells addObject:cellForIndexPath];
    }];
    return [NSArray arrayWithArray:sortedCells];
}

@end
0

In two dimensional space there isn't a single possible order. If self.collectionView.visibleCells doesn't have the order you'd wish for, sort the cells the way you want to, by comparing their frames, or their index paths.

0

Extending Ben answer, here is an extension to UICollectionView that does the job:

extension UICollectionView {
    var orderedVisibleCells: [UICollectionViewCell] {
        let cells = self.indexPathsForVisibleItems.sorted { (left, right) in
            return left.section < right.section || (left.section == right.section && left.row < right.row)
        }.compactMap { index in
            return self.cellForItem(at: index)
        }
        return cells
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.