我正在开发一个照片库应用程序,该应用程序主要由一个导航 Controller 组成,在该 Controller 上加载了 Collection View 的实例。每个 Collection View 单元格都包含一个 UIImageView 和一个图像名称标签。单元异步加载图像。
第一次加载每个 Collection View 时,这一切都工作正常,但是如果您后退到上一个 Collection View 并再次前进,标签就会消失。
我认为这一定与异步加载图像有关,就好像我删除图像加载一样,标签很好,有正确的文本并且不会消失。
我不确定图像加载哪里出了问题...
各个组件是:
使用此扩展方法加载图像:
extension UIImageView {
public func imageFromServerURL(url: URL) {
if ImageData.realPhotoCache.keys.contains(url.absoluteString){
self.image = ImageData.realPhotoCache[url.absoluteString];
}else{
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error)
return
}
DispatchQueue.main.async(execute: { () -> Void in
let image = UIImage(data: data!)
ImageData.realPhotoCache[url.absoluteString] = image;
self.image = image
})
}).resume()
}
}}
Collection View 的单元格的结构如下:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell: UICollectionViewCell;
cell = collectionView.dequeueReusableCell(withReuseIdentifier: photoCellReuseIdentifier, for: indexPath);
let imageProvider = self.imageProviderForIndexPath(indexPath: indexPath);
(cell as! tsPhotoCollectionViewCell).photoView.imageFromServerURL(url: imageProvider.GetThumbImageUrl());
(cell as! tsPhotoCollectionViewCell).titleLabel.text = imageProvider.GetImageTitle()!;
return cell
}
Collection View 在返回时被重置,如下所示:
func reset(){
photoProviders = [ImageDataProvider]();
self.collectionView?.reloadSections(IndexSet(integer: 0))
startLoad()
}
override func viewWillAppear(_ animated: Bool) {
if(hasNavigatedAway){
hasNavigatedAway = false;
self.reset();
}
}
集合的第一次加载通常没问题(单元格为绿色,标签为红色):
但是离开并返回 Collection View 时,标签消失了:
有时标签似乎也会随着滚动而来来去去。我已经尝试了我能想到的一切,但没有任何运气..
最佳答案
从您的屏幕截图来看,UILabels 似乎通过扩展 UIImageView 将其高度压缩为 0。尝试增加 UILabel 的垂直内容压缩阻力优先级,例如增加到 1000,以便它变得不可压缩(并且反过来,使自动布局引擎压缩 UIImageView 或间距 - 取决于您的约束)。
关于ios - UICollectionViewCell 中异步加载图像导致标签消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49245450/