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
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)
}
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 { }
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")
}
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.