如何获取 CollectionView willDisplayCell 中的最后一个对象?

How can I get last object in CollectionView willDisplayCell?

如何检测 UICollectionView 在 willDisplayCell 中的最后一个可见对象?在 UITableView 中,我可以使用以下代码来完成:-

-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
    //DO SOMETHING HERE
    }

}

那么对于UICollectionView,我该怎么做呢?

-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    {
      //HOW CAN I DO THIS SAME LIKE TABLEVIEW?
    }
}

indexPathsForVisibleItems 的问题是 - 根据 https://developer.apple.com/documentation/uikit/uicollectionview/1618020-indexpathsforvisibleitems?language=objc - 它包含一个

unsorted array of NSIndexPath objects

因此你必须使用不同的方法:

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == collectionView.numberOfSections - 1 && indexPath.row == [collectionView numberOfItemsInSection:collectionView.numberOfSections - 1] - 1) {
        // last row
    } else {
        // "regular" row
    }
}

完全一样:-

-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{     
     if([indexPath row] == ((NSIndexPath*)[[collectionView indexPathsForVisibleItems] lastObject]).row){
         //DO SOMETHING HERE
     }       
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    for (UICollectionViewCell *cell in [self.collection_NewCandidates visibleCells]) {
        NSIndexPath *indexPath = [self.collection_NewCandidates indexPathForCell:cell];
        NSLog(@"your cell index %ld",(long)indexPath.item);
    }
}