2017-04-07 60 views
0

所以在我的集合视图单元格中我有文本和图像:这是我在CollectionViewLayout中的代码。为什么我的Collectionview cell.image不见了,搞砸了?

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 

    if let content = HomeCollectionViewController.posts[indexPath.item].content { 
     let spaceForPostContentLabel = NSString(string: content).boundingRect(with: CGSize(width: view.frame.width - 32, height: 120), options: NSStringDrawingOptions.usesFontLeading.union(NSStringDrawingOptions.usesLineFragmentOrigin), attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 15)], context: nil) 

     if HomeCollectionViewController.posts[indexPath.item].imageURL != nil { 
      return CGSize(width: view.frame.width, height: spaceForPostContentLabel.height + postImageViewOriginHeight + 168.0) 
     } else { 
      return CGSize(width: view.frame.width, height: spaceForPostContentLabel.height + 152.5) 
     } 
    } else { 
     return CGSize(width: view.frame.width, height: 408.5) 
    } 
} 

一切都很好,当它第一次加载。但是当我向下滚动并再次滚动时,一切都变得混乱起来,图像消失了,图像应该已经存在一个巨大的空白空间。这是否与dequeReusableIdentifier有关?

注:此错误仅发生在第一个单元,其他单元有图像由于如何出队工作正常工作

回答

0

这可能发生。即使您有100个单元格,同时加载的单元格也是有限制的,因此在此限制之后,您将在滚动时重新使用旧单元格。

我已经遇到了相同的问题,有时主要是在使用图像时,我发现的最佳方法是使用缓存来处理图像。

下面我用AlamofireImage创建缓存发布一个例子(但你可以使用雨燕的库提供您喜欢的缓存,甚至内置的缓存。

import AlamofireImage 

let imageCache = AutoPurgingImageCache() 

class CustomImageView: UIImageView { 

    var imageUrlString: String? 

    func loadImageFromURL(_ urlString: String){ 

      imageUrlString = urlString 

      let url = URL(string: urlString) 

      image = nil 

      if let imageFromCache = imageCache.image(withIdentifier: urlString) { 
       self.image = imageFromCache 
       return 
      } 

      URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in 

       if error != nil { 
        print(error) 
        return 
       } 

       DispatchQueue.main.async(execute: { 

        let imageToCache = UIImage(data: data!) 

        if self.imageUrlString == urlString { 
         self.image = imageToCache 
        } 

        imageCache.add(imageToCache!, withIdentifier: urlString) 
       }) 

      }).resume() 
    } 

} 

基本上我创建UIImageView的子类,并添加图像URL作为我要保存在缓存中的图像的关键字每当我尝试从互联网上加载图像时,我检查图像是否已经不在缓存中,如果是这样,我将图像设置为缓存中的图像,如果没有,我将异步加载它从互联网上。

+0

你确定吗?这仍然不适用于我 –