2017-04-07 57 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

你確定嗎?這仍然不適用於我 –