Search code examples
iosswiftuicollectionviewcelluicollectionreusableview

UICollectionViewCells deque returns wrong cell


I have a CollectionView, I use the cells to display videos and I also store some other data on variables. And whenever I scroll I reuse previous cells using the following code:

let cell = collectionView.dequeueReusableCellWithReuseIdentifier("profileCell", forIndexPath: indexPath) as! ProfileCollectionViewCell

But I noticed that when I am using an indexPath I have previously used, I do not get back the same cell as previously but another cell apparently at a random order. I would like to avoid reloading the videos when it is not necessary.

Is there a way for me to get the same cell used with the same indexPath?

Thanks, Carlos


Solution

  • That's how collectionView.dequeueReusableCellWithReuseIdentifier works. If you want to go around this functionality you could save all cells that are created in an array and then instead of dequeueing you could fetch the one with the video already loaded. However, if you use some framework that caches the videos after loading them you shouldn't need to deal with this at all.

    var cells: [CustomCollectionViewCell] = []
    
        func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
            var cell:CustomCollectionViewCell?
            if cells.count >= indexPath.row {
                cell = cells[indexPath.row]
            } else {
                cell = CustomCollectionViewCell()
                //setup cell
                cells.append(cell)
            }
    
            return cell!
        }
    

    Disclaimer:

    This solution is a hack. As mentioned by @Async in the comment below this solution will use a lot of memory if you create a lot of cells.