UIcollectionView奇怪的细胞回收行为

问题描述 投票:0回答:1

我有一个流式布局的UICollectionView,大约140个单元格,每个单元格都有一个简单的UITextView。当一个单元被回收时,我将textView弹出到缓存上,稍后在新单元格上重复使用它。一切顺利,直到我到达底部并向上滚动。在那一点上,我可以看到CollectionView的单元格号为85,但是在单元格85显示之前,它再次为单元格87重新循环,所以我现在丢失了我刚准备的单元格的内容。

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

   let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FormCell", for: indexPath) as! FormCollectionViewCell
   let textView = Cache.vendTextView()
   textView.text = "\(indexPath.row)"
   cell.addSubview(textView)
   cell.textView = textView

   return cell

}

并在UIcollectionViewCelC上

override func prepareForReuse() {

   super.prepareForRuse()
   self.textView.removeFromSuperView()
   Cache.returnView(self.textView)

}

我原以为在调用cellForItemAtIndexPath()之后,它会从可重用的单元池中删除,但它似乎会立即再次被回收用于相邻的单元。也许是一个bug或者我可能误解了UICollectionView的正常行为?

enter image description here

ios swift uicollectionview uicollectionviewcell
1个回答
0
投票

据我所知,你要做的只是跟踪细胞内容 - 当细胞消失时保存它,并在它再次返回时恢复它。由于以下几个原因,你正在做的事情不能很好地运作:

  1. vendTextViewreturnView不接受indexPath作为参数 - 你的缓存存储东西并取出东西,但是你无法知道你正在存储/取出它以获得正确的单元格
  2. 缓存整个文本视图没有意义 - 为什么不缓存文本?

尝试类似的东西:

让你的FormCollectionViewCell将文本视图作为子视图,并修改你的代码,如下所示:

class YourViewController : UIViewController, UICollectionViewDataSource, UICollectionViewDelegate 
{
    var texts = [IndexPath : String]()

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

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FormCell", for: indexPath)
        if let formCell = cell as? FormCollectionViewCell {
            cell.textView.text = texts[indexPath]

            return cell
        }
    }

    func collectionView(_ collectionView: UICollectionView, 
        didEndDisplaying cell: UICollectionViewCell, 
               forItemAt indexPath: IndexPath)
    {
        if let formCell = cell as? FormCollectionViewCell {
        {
            texts[indexPath] = formCell.textView.text
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.