【问题标题】:Collection View reusable cell issue while scrolling滚动时收集视图可重复使用的单元格问题
【发布时间】:2020-05-25 16:45:03
【问题描述】:

我正在使用集合视图在列表中显示 gif。 现在在集合视图中向上或向下滚动单元格时面临单元格可重用问题。

就像 itemA 在列表中的 第一 位和 itemB 在列表中的 第二 位. 但是当我在集合视图中滚动数据时。物品的位置放错了地方。就像某个时间 itemA 排在第 5 位或有时在列表中的任何位置。 我知道我认为这是可重复使用的电池的用途,但不知道如何解决这个问题。 请帮忙。

集合视图 cellForItemAt

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

    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GifCell", for: indexPath as IndexPath) as? GifCell else {
        fatalError()
    }

    if gifArr.count > 0 {

        let urlString = self.gifArr[indexPath.row]
        let url = URL(string: urlString)!

        DispatchQueue.global().async {
            let imageData = try? Data(contentsOf: url)
            let imageData3 = FLAnimatedImage(animatedGIFData: imageData) // this is the 3rd pary library to show the gifs on UIimageview's
            DispatchQueue.main.async {
                cell.imageView.animatedImage = imageData3
                cell.textLabel.text = String(indexPath.row)
            }
        }
    }
    return cell
}

【问题讨论】:

标签: ios iphone swift3 uicollectionview swift4


【解决方案1】:

GifCell 中你可以实现prepareForReuse() 方法:

执行任何必要的清理工作以准备再次使用视图。

override func prepareForReuse() {
    super.prepareForReuse()
    imageView.animatedImage = nil
    textLabel.text = ""
}

注意: 此时,每次调用cellForItemAt 方法时,都会重新加载url,所以稍后,您可能想找到一种方法来缓存图像而不是不断地重新加载它们。

【讨论】:

    【解决方案2】:

    第一个解决方案:您可以缓存数据,每次检查是否有,使用您的缓存。 您可以使用this link,但将UIImage 替换为礼物类型!

    或 试试这个,我没测试过

    if let giftAny = UserDefaults.standard.value(forKey: "giftUrl") {
      //cast giftAny to Data
      // use cached gift
    } else {
      // cache gift
      let giftData = try? Data(contentsOf: url)
      UserDefaults.standard.setValue(giftData, forKeyPath: "giftUrl")
      //use gift
    }
    

    第二种解决方案:不要重复使用单元格

        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = UICollectionViewCell(style: .default, reuseIdentifier:"Cell")
            return cell
        }
    

    但是在这种情况下,如果你有很多单元格,内存泄漏是不可避免的。

    【讨论】:

    • 请告诉我如何缓存 gif 的数据。
    • FLAnimatedImage(animatedGIFData: imageData)的类型是什么?
    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    相关资源
    最近更新 更多