如果可见,UICollectionViewCell 不更新图像
UICollectionViewCell not updating image if visible
我有一个 CollectionView,它在加载后显示缩略图。一开始,图片没有存储在设备上,所以它们是从服务器上获取的。在从服务器获取这些图像后的回调方法中,它们的单元格没有得到更新,我需要将它们滚动出屏幕,然后它们得到更新。我在另一个应用程序中有类似的机制,一切正常,但我找不到区别。下面是代码的一些部分,以便更好地理解我的工作。
这是我在检查是否已从服务器获取缩略图后设置图像的代码。如果有,直接设置,如果没有,使用Alamofire获取图片,加载完成后更新。
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.reuseIdentifier, for: indexPath) as! PictureCollectionViewCell
/* Set thumbnail to the cell */
if let thumbnail = pictures[indexPath.row].thumbnail {
cell.imageView.image = thumbnail
} else {
pictures[indexPath.row].retrievePicture(thumbnail: true, completion: { picture in
cell.imageView.image = picture
})
}
return cell
}
如前所述,在我将单元格滚动出可见屏幕区域之前,它不会更新。单元格或 collectionView 重新加载没有解决问题。有什么想法吗?
提前致谢。
因为块在后台线程中执行。您必须在主线程中更新 UI。使用下面的代码
pictures[indexPath.row].retrievePicture(thumbnail: true, completion: { picture in
DispatchQueue.main.async {
cell.imageView.image = picture
}
})
您可能会发现,最好重新加载 indexPath 中的项目,而不是使用以下方法重新加载整个 table:
collectionView.reloadItemsAtIndexPaths(yourIndexPath)
提取可能发生在后台线程中,因此您的回调函数也会从中调用。 UI 无法从后台线程更新。
所以在你的抓取回调中尝试使用这样的东西:
DispatchQueue.main.async {
collectionView.reloadData()
}
或者
DispatchQueue.main.async {
collectionView.reloadItems(indexPaths)
}
好的,伙计们,这是你能想象到的最愚蠢的错误。从异步回调方法更新 UI 就可以正常工作。我只是忘了从异步任务中调用回调方法。问题已解决,感谢您的帮助。
我有一个 CollectionView,它在加载后显示缩略图。一开始,图片没有存储在设备上,所以它们是从服务器上获取的。在从服务器获取这些图像后的回调方法中,它们的单元格没有得到更新,我需要将它们滚动出屏幕,然后它们得到更新。我在另一个应用程序中有类似的机制,一切正常,但我找不到区别。下面是代码的一些部分,以便更好地理解我的工作。
这是我在检查是否已从服务器获取缩略图后设置图像的代码。如果有,直接设置,如果没有,使用Alamofire获取图片,加载完成后更新。
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.reuseIdentifier, for: indexPath) as! PictureCollectionViewCell
/* Set thumbnail to the cell */
if let thumbnail = pictures[indexPath.row].thumbnail {
cell.imageView.image = thumbnail
} else {
pictures[indexPath.row].retrievePicture(thumbnail: true, completion: { picture in
cell.imageView.image = picture
})
}
return cell
}
如前所述,在我将单元格滚动出可见屏幕区域之前,它不会更新。单元格或 collectionView 重新加载没有解决问题。有什么想法吗?
提前致谢。
因为块在后台线程中执行。您必须在主线程中更新 UI。使用下面的代码
pictures[indexPath.row].retrievePicture(thumbnail: true, completion: { picture in
DispatchQueue.main.async {
cell.imageView.image = picture
}
})
您可能会发现,最好重新加载 indexPath 中的项目,而不是使用以下方法重新加载整个 table:
collectionView.reloadItemsAtIndexPaths(yourIndexPath)
提取可能发生在后台线程中,因此您的回调函数也会从中调用。 UI 无法从后台线程更新。 所以在你的抓取回调中尝试使用这样的东西:
DispatchQueue.main.async {
collectionView.reloadData()
}
或者
DispatchQueue.main.async {
collectionView.reloadItems(indexPaths)
}
好的,伙计们,这是你能想象到的最愚蠢的错误。从异步回调方法更新 UI 就可以正常工作。我只是忘了从异步任务中调用回调方法。问题已解决,感谢您的帮助。