2017-02-23 57 views
0

我的圖片和一些標籤位於我的單元格內。如果我的頁面上有更多的單元格,那麼向下滾動然後備份會立即加載不同的圖像,然後加載原始照片。我已經閱讀了各地的StackOverflow看看什麼會在我的情況下工作,但到目前爲止我找不到任何東西,因爲我的UITableView是在一個ViewController內。UITableViewCell中的圖像在向下滾動並備份後發生變化

這裏是我我的內容加載到我的手機:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! PostTableViewCell 
    // Configure the cell... 
    let post = self.posts[indexPath.row] as! [String: AnyObject] 
    cell.titleLabel.text = post["title"] as? String 
    cell.priceLabel.text = post["price"] as? String 
    if let imageName = post["image"] as? String { 
     let imageRef = FIRStorage.storage().reference().child("images/\(imageName)") 
     imageRef.data(withMaxSize: 25 * 1024 * 1024, completion: { (data, error) -> Void in if error == nil { 
      let image = UIImage(data: data!) 
      UIView.animate(withDuration: 0.4, animations: { 
       cell.titleLabel.alpha = 1 
       cell.postImageView.alpha = 1 
       cell.priceLabel.alpha = 1 
      cell.postImageView.image = image 
      }) 
     } else { 
      print("Error occured during image download: \(error?.localizedDescription)") 
      } 
     }) 
    } 
    return cell 
} 

有什麼辦法我可以改變tableView.dequeueReusableCell的東西不同,所以不會發生這種情況?

+0

用'willDisplayCell'方法嘗試設置圖像 –

+0

爲什麼要爲圖像設置動畫效果?只需在動畫之前設置它。 –

+0

@AdrianBobrowski我應該設置整個函數來使用willDisplayCell嗎? – gabe

回答

3

在你的表視圖單元格PostTableViewCell需要實現的方法

override func prepareForReuse() { 
    super.prepareForReuse() 
    self.postImageView.image = nil 
    // Set cell to initial state here, reset or set values 
} 

的細胞握緊手中的舊內容

+0

這是行得通的,但是我擔心緩慢/計量互聯網的用戶連接每次滾動時都必須加載圖像。有什麼辦法可以緩存圖片嗎? – gabe

+0

要做到這一點,你需要將加載圖像中的服務器代碼中的圖像加載到表格單元代碼中,但我並不熟悉Fire基礎知道如何做到這一點。他們必須有一個應用程序內存存儲區,您可以利用 – bolnad

+0

Apple文檔中提到的prepareForReuse:「出於性能方面的原因,您應該只重置與內容無關的單元格屬性,例如alpha,編輯和選擇狀態。 「但是我的UITableView沒有很多單元,所以這個解決方案對我來說完美無缺! – abanet

0

我想你遇到的問題,因爲在更新完成後在細胞內塊。如果單元格在完成塊運行之前滾動出視圖,它將被重用於不同的行,但是您仍然在爲前一行設置圖像。

試試這個:

imageRef.data(withMaxSize: 25 * 1024 * 1024, completion: { (data, error) -> Void in if error == nil { 
     if let cell = self.tableView.cellForRow(at: indexPath) as? PostTableViewCell { 
      let image = UIImage(data: data!) 
      UIView.animate(withDuration: 0.4, animations: { 
       cell.titleLabel.alpha = 1 
       cell.postImageView.alpha = 1 
       cell.priceLabel.alpha = 1 
       cell.postImageView.image = image 
      } 
     }) 

不是依靠電池仍然是可見的,這將嘗試從基於indexPath表視圖得到它。如果不再可見,cellForRow(at:)將返回nil