在加载新的单元格数据之前,需要用以前的单元格数据填充UICollectionViewCell,需要实现PrepareForReuse

问题描述

我的UICollectionView有一个问题,问题是,如果滚动足够快(甚至不够快),则在显示重用之前的单元格中的数据将显示一两秒钟,然后再显示新数据。

这是有关更多情况的视频(youtube视频链接):https://youtu.be/I63hBuxBGI0

这是cellForItemAt内部的代码

func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

if let post = FeedElements[indexPath.row] as? FeedPost {

  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",for: indexPath) as! FeedCollectionViewCell

 
  cell.delegate = self
  cell.post = post
  cell.commentButton.tag =  indexPath.row

  // assigning all of the data 
  cell.captionLabel.text = post.caption
  cell.locationLabel.text = post.location
  cell.timeAgoLabel.text = post.timeAgoString
  cell.setUpElements()
  cell.prepareForReuse()
  return cell
}
}

numberOfRowsInSection内部的代码

func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
    return FeedElements.count
}

我很确定我需要实现prepareForReuse(),但是我不确定该怎么做,也找不到在线有用的东西。

非常感谢!

解决方法

您需要像这样在prepareForReuse类中添加feedCollectionViewCell

class feedCollectionViewCell: UITableViewCell {
    override func prepareForReuse() {
        super.prepareForReuse()

  // Reset your values here as you want ... 

        self.post = nil
        self.commentButton.tag =  0

        // assigning all of the data
        self.captionLabel.text = nil
        self.locationLabel.text = nil
        self.timeAgoLabel.text = nil
    }
}