2017-08-01 49 views
1

我試圖做一個表格,當圖像完成加載(異步)時,單元格上的imageView將alpha從0更改爲1。 我做了什麼似乎只是將圖像顯示在一個而不是淡入。我確定它是某種競爭條件,但我是iOS新手,並且不知道如何解決這個問題。任何輸入都會很棒。 這裏是我的代碼:異步加載動畫cell.imageview

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 

    //Configure the cell... 
    let episode = episodes[indexPath.row] 

    cell.textLabel?.text = episode.title 

    cell.detailTextLabel?.text = episode.content 

    let logoUrl = URL(string: episode.logoUrl!) 

    if (episode.logoImage == nil){ 
     episode.logoImage = UIImage() 
     DispatchQueue.global().async { 
      let data = try? Data(contentsOf: logoUrl!) //make sure your image in this url does exist, otherwise unwrap in a if let check/try-catch 
      DispatchQueue.main.async { 
       episode.logoImage = UIImage(data: data!) 
       cell.imageView?.image = episode.logoImage 
       self.episodesTable.reloadData() 
       cell.imageView?.alpha = 0 
       UIView.animate(withDuration: 1, animations: { 
        cell.imageView?.alpha = 1 
       }) 

      } 
     } 
    } else{ 
     cell.imageView?.image = episode.logoImage 
    } 

    return cell 
} 
+1

是否需要'self.episodesTable.reloadData()?嘗試刪除它可能嗎? –

回答

1

reloadData()調用導致重裝的所有單元格,包括您試圖動畫之一。我的建議是用它的索引路徑標記你的單元格。在異步調用之後,檢查它是否仍然呈現正確的數據並在不重新加載整個表格視圖的情況下進行動畫處理。

// ... 
cell.tag = indexPath.item 
DispatchQueue.global().async { 
    // async load 
    DispatchQueue.main.async { 
     guard cell.tag == indexPath.item else { return } 
     cell.imageView?.alpha = 0.0 
     cell.imageView?.image = image 
     // animate 
    } 
} 
// ... 
+0

你說得對。重新加載是造成這個問題。此外,我創建了一個自定義單元格併爲其製作UIImage,而不是使用默認的單元格圖像。 – iCediCe

3

請先動畫爲1

cell.imageView?.alpha = 0 
UIView.animate(withDuration: 1, animations: { 
        cell.imageView?.alpha = 1 
       }) 

而且之前設置透明度爲0,你不需要重新加載表。刪除self.episodesTable.reloadData()

您正在跨越後臺線程並從該線程內的url加載圖像。如果在用戶滾動單元格之間呢?你將在錯誤的單元格上留下錯誤的圖像(因爲單元格重用,那就是)。

我的建議是使用SDWebImageCache,並使用它的完成塊爲alpha生成動畫。

// Changing animation duration to 0.2 seconds from 1 second 
if(cacheType == SDImageCacheTypeNone) { 
    cell.imageView?.alpha = 0 
    [UIView animateWithDuration:0.2 animations:^{ 
     cell.imageView?.alpha = 1; 
    }]; 
} 
+1

你是對的。然而,這是在我的代碼準備好了,不知道它是如何迷失在這個問題。但是這並不能解決圖像仍然不能淡入的問題,只是出現。我用缺失的一行來解決問題。 – iCediCe