ios - UICollectionViewCell 中异步加载图像导致标签消失

标签 ios swift uicollectionview uiimageview uicollectionviewcell

我正在开发一个照片库应用程序,该应用程序主要由一个导航 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();
    }
}

集合的第一次加载通常没问题(单元格为绿色,标签为红色):

https://imgur.com/g3p03yF

但是离开并返回 Collection View 时,标签消失了:

https://imgur.com/If2FQZS

有时标签似乎也会随着滚动而来来去去。我已经尝试了我能想到的一切,但没有任何运气..

最佳答案

从您的屏幕截图来看,UILabels 似乎通过扩展 UIImageView 将其高度压缩为 0。尝试增加 UILabel 的垂直内容压缩阻力优先级,例如增加到 1000,以便它变得不可压缩(并且反过来,使自动布局引擎压缩 UIImageView 或间距 - 取决于您的约束)。

关于ios - UICollectionViewCell 中异步加载图像导致标签消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49245450/

相关文章:

ios - Failed to parse app's Info.plist appcelerator studio 错误

ios - 如何使用 Optionals 来阻止 Swift 中的编译器错误

ios - UITableView - 辞去外部触摸的第一响应者

swift - 如何在 Swift 中制作经过身份验证的 HTTPS 帖子?

swift - 如何根据 RTL/LTR 连接字符串

ios - 何时释放为 UICollectionViewCell 光栅化分配的内存?

iphone - 如何组合 View 层级以增强动画性能?

swift - 地理编码地址不提供经纬度

xcode - 旋转后 UICollectionView 单元格不水平

ios - Swift - UICollectionView removeAll() 暂时清除单元格