2017-02-23 60 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