在Swift中翠鸟下载失败时在UICollectionViewCell中隐藏UIImageView



我想在UICollectionViewCell中隐藏我的UIImageView并在Kingfisher下载失败时更新单元格大小。

我的setData函数在cellForItem中调用

func setData(with data: Article?, indexPath: IndexPath) {
guard let data = data else { return }

if let imageUrl = data.urlToImage, imageUrl.isValidURL, let url = URL(string: imageUrl.addingPercentEncoding) {
self.newsImageView.kf.setImage(with: url, options: [.transition(.fade(0.3))]) { [weak self] result in
guard let self = self else { return }
switch result {
case .success(_):
self.newsImageView.isHidden = false
case .failure(let error):
self.newsImageView.isHidden = true
// the above line is not enough I should also update cell size this is the my actual problem.
}
}
} else {
self.newsImageView.isHidden = true
}

}

CellForItem

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let homeCell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeCollectionViewCell.identifier, for: indexPath) as? HomeCollectionViewCell,
let article = viewModel.getArticle(at: indexPath)

else {
let emptyCell = collectionView.dequeueReusableCell(withReuseIdentifier: EmptyArticlesCollectionViewCell.identifier, for: indexPath)
return emptyCell
}

homeCell.configure(with: article, indexPath: indexPath)
return homeCell
}

HomeCollectionViewCell.swift

class HomeCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var homeCollectionViewCellComponent: HomeCollectionViewCellComponent!

.
.
.
func configure(with data: Article, indexPath: IndexPath) {
homeCollectionViewCellComponent.setData(with: data, indexPath: indexPath)
}

override func prepareForReuse() {
homeCollectionViewCellComponent.prepareForReuse()
}
}

您应该将setData调用直接发生在cellForItemAt中。然后在回调中,你可以隐藏图像视图(就像你正在做的那样)然后立即在回调中调用collectionView.reconfigureItems(at:)(如果使用iOS 15+)或collectionView.reloadItems(at:)

您可能需要在单元格(或者可能是文章本身)上实现bool标志,以便在无法加载图像时使用。否则,当单元格重新加载时,你可能会进入重新加载单元格的无限循环。

最新更新