Check if cell in indexPath is visible on UICollectionView screen

I have CollectionViewone that displays images to the user. I download them in the background, and when the download is complete, I call the following func to update collectionViewCelland display the image.

func handlePhotoDownloadCompletion(notification : NSNotification) {
    let userInfo:Dictionary<String,String!> = notification.userInfo as! Dictionary<String,String!>
    let id = userInfo["id"]
    let index = users_cities.indexOf({$0.id == id})
    if index != nil {
        let indexPath = NSIndexPath(forRow: index!, inSection: 0)
        let cell = followedCollectionView.cellForItemAtIndexPath(indexPath) as! FeaturedCitiesCollectionViewCell
        if (users_cities[index!].image != nil) {
            cell.backgroundImageView.image = users_cities[index!].image!
        }
    }
}

This works fine if the cell is currently displayed on the screen, however, if it is not, I get fatal error: unexpectedly found nil while unwrapping an Optional valuethe following line:

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

Now this function does not even need to be called if the ViewCell collection is not yet visible, because in this case the image will be set in the method cellForItemAtIndexPathin any case.

, , , , , , . collectionView.visibleCells(), , , .

+4
3

followedCollectionView.indexPathsForVisibleItems() visibleIndexPaths , indexPath visibleIndexPaths , - .

+8

if collectionView.cellForItem(at: indexPath) == nil { }. CollectionView , .

:

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

if let cell = followedCollectionView.cellForItemAtIndexPath(indexPath) as? FeaturedCitiesCollectionViewCell { }

+1

Nested UICollectionViews just need not be scrolled at all, so that the content of contentOffset is never provided, and therefore iOS understands that all cells are always visible. In this case, you can use the borders of the screen as a link:

    let cellRect = cell.contentView.convert(cell.contentView.bounds, to: UIScreen.main.coordinateSpace)
    if UIScreen.main.bounds.intersects(cellRect) {
        print("cell is visible")
    }
+1
source

All Articles