Check whether cell at indexPath is visible on screen UICollectionView

后端 未结 4 874
春和景丽
春和景丽 2021-02-19 18:44

I have a CollectionView which displays images to the user. I download these in the background, and when the download is complete I call the following func to update

相关标签:
4条回答
  • 2021-02-19 19:26

    You can get current index by

    // Called before the cell is displayed    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        print(indexPath.row)
    }
    
    // Called when the cell is displayed
    func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        print(indexPath.row)
    }
    
    0 讨论(0)
  • 2021-02-19 19:32

    You can simply use if collectionView.cellForItem(at: indexPath) == nil { }. The collectionView will only return a cell if it is visible.

    Or in your case specifically change:

    let cell = followedCollectionView.cellForItemAtIndexPath(indexPath) as! FeaturedCitiesCollectionViewCell
    

    to:

    if let cell = followedCollectionView.cellForItemAtIndexPath(indexPath) as? FeaturedCitiesCollectionViewCell { }
    
    0 讨论(0)
  • 2021-02-19 19:35

    Nested UICollectionViews need oft to not scroll at all, so that no contentOffset is ever provided and thus iOS understands all cells as being always visible. In that case it is possible to take the screen boundaries as reference:

        let cellRect = cell.contentView.convert(cell.contentView.bounds, to: UIScreen.main.coordinateSpace)
        if UIScreen.main.bounds.intersects(cellRect) {
            print("cell is visible")
        }
    
    0 讨论(0)
  • 2021-02-19 19:47

    Get current available cells

    // get visible cells 
    let visibleIndexPaths = followedCollectionView.indexPathsForVisibleItems
    

    Then check if your indexPath is contained in the visibleIndexPaths array or not, before doing anything with cells.

    0 讨论(0)
提交回复
热议问题