使用 CoreData 中的图像填充 UICollectionView

Populate UICollectionView with images from CoreData

我正在尝试使用 CoreData 数据库中的数据填充我的 UICollectionView。问题是我想在 Collection Cell 中显示一张照片并使用数据创建 UIImage - 这个任务可能需要一段时间。使用当前解决方案,图像大约加载。 3 秒后,但所有其他数据已显示在集合视图中。

我应该如何添加加载叠加并知道何时所有图像都准备好隐藏它,或者什么是正确的方法?

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: viewModel.reuseIdentifier, for: indexPath) as? LocationCollectionViewCell {
    
        cell.name.text = viewModel.locations[indexPath.row].name
        cell.unlocked.text = viewModel.locations[indexPath.row].unlocked ? "Unlocked" : "Locked"
        
        if let data = viewModel.locations[indexPath.row].image {
            DispatchQueue.global(qos: .background).async {
                let image = UIImage(data: data)
                
                DispatchQueue.main.async {
                    cell.image.image = self.viewModel.locations[indexPath.row].unlocked ? image : image?.grayscale()
                }
            }
        } else {
            cell.image.image = viewModel.locations[indexPath.row].unlocked ? UIImage(named: "noun_Akropolis_403786") : UIImage(named: "noun_Akropolis_403786")?.grayscale()
        }
        
        return cell
        
    } else {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: viewModel.reuseIdentifier, for: indexPath)
        return cell
    }
}

所以@peter 你可以尝试做以下事情:

  1. 您可以在单元格中添加加载器,并且 show/hide 当图像为 nil 或没有时它。
  2. 为此创建一个数组,当加载任何图像时,只需在其中附加该索引即可。直到数组不包含所有索引在屏幕中显示加载器否则隐藏加载器。
  3. 要处理错误,您可以简单地使用 try catch。如果图像未加载或失败,则您应该提供虚拟或占位符图像。这样加载程序将被一次性删除。