检查indexPath上的单元格是否在屏幕UICollectionView上可见

问题描述 投票:9回答:3

我有一个CollectionView,向用户显示图像。我在后台下载这些,当下载完成后,我调用以下函数来更新collectionViewCell并显示图像。

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!
        }
    }
}

如果单元格当前在屏幕上可见,则此方法很有效,但如果不是,则在以下行中出现fatal error: unexpectedly found nil while unwrapping an Optional value错误:

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

现在,如果collectionViewCell尚未可见,则甚至不需要调用此函数,因为在这种情况下,无论如何都将在cellForItemAtIndexPath方法中设置图像。

因此我的问题是,如何更改此函数以检查我们正在处理的单元格当前是否可见。我知道collectionView.visibleCells()然而,我不知道如何在这里应用它。

ios swift uicollectionview uicollectionviewcell nsindexpath
3个回答
17
投票

获取当前可用的单元格

// get visible cells 
let visibleIndexPaths = followedCollectionView.indexPathsForVisibleItems()

然后在对细胞做任何事情之前检查你的indexPath是否包含在visibleIndexPaths中。


6
投票

嵌套的UICollectionViews根本不需要滚动,因此不会提供任何contentOffset,因此iOS会将所有单元格理解为始终可见。在这种情况下,可以将屏幕边界作为参考:

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

1
投票

你可以简单地使用if collectionView.cellForItem(at: indexPath) == nil { }。只有可见时,collectionView才会返回一个单元格。

或者在您的情况下具体改变:

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

至:

if let cell = followedCollectionView.cellForItemAtIndexPath(indexPath) as? FeaturedCitiesCollectionViewCell { }
© www.soinside.com 2019 - 2024. All rights reserved.