检查indexPath的单元格是否在屏幕UICollectionView上可见 [英] Check whether cell at indexPath is visible on screen UICollectionView

查看:174
本文介绍了检查indexPath的单元格是否在屏幕UICollectionView上可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 CollectionView ,它可以向用户显示图像.我在后台下载了这些文件,下载完成后,我调用以下函数来更新 collectionViewCell 并显示图像.

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 the collectionViewCell and 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!
        }
    }
}

如果当前在屏幕上可见该单元格,则效果很好,但是如果不是,我会得到一个致命错误:在以下行解开一个可选值时意外发现nil 错误:

This works great if the cell is currently visible on screen, however if it is not I get a fatal error: unexpectedly found nil while unwrapping an Optional value error on the following line :

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

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

Now this function does not even need to be called if the collectionViewCell is not yet visible, because in this case the image will be set in the cellForItemAtIndexPath method anyway.

因此,我的问题是,如何更改此功能以检查正在处理的单元格当前是否可见.我知道 collectionView.visibleCells(),但是,我不确定如何在此处应用它.

Hence my question, how can I alter this function to check whether the cell we are dealing with is currently visible or not. I know of the collectionView.visibleCells() however, I am not sure how to apply it here.

推荐答案

获取当前可用的单元格

// get visible cells 
let visibleIndexPaths = followedCollectionView.indexPathsForVisibleItems

然后在对单元格执行任何操作之前,检查 indexPath 是否包含在 visibleIndexPaths 数组中.

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

这篇关于检查indexPath的单元格是否在屏幕UICollectionView上可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆