2017-06-18 79 views
-3

我在表格视图单元格中存在图像问题 图像是从Google Firebase下载的,并且在每个单元格中都有一个 但是,当我向上或向下滚动时,图像会自动更改索引 这是我的代码,有人可以帮助我吗?非常感谢!表格视图中的图像

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    if postsArray[indexPath.row].imageNoImage == true{ 

     let cell = tableView.dequeueReusableCell(withIdentifier: "imageLook", for: indexPath) as! imageLookTableViewCell 
     cell.authorLabel.text = self.postsArray[indexPath.row].author 
     cell.likesCountLabel.text = "\(self.postsArray[indexPath.row].likes!)" 
     cell.postID = postsArray[indexPath.row].postId 
     cell.textViewPost.text = self.postsArray[indexPath.row].textPost 
     let url = URL(string: postsArray[indexPath.row].pathToImage as! String) 
     if url != nil { 
      DispatchQueue.global().async { 
       let data = try? Data(contentsOf: url!) 
       DispatchQueue.main.async { 
        if data != nil { 
         cell.imagePost.image = UIImage(data:data!) 
        }else{ 

        } 
       } 
      } 
     } 
     for person in self.postsArray[indexPath.row].peopleWhoLike { 
      if person == FIRAuth.auth()!.currentUser!.uid { 
       cell.likesBtn.isHidden = false 
       break 
      } 
     } 

     return cell 
    } 
+1

不要问有上百万的答案对SO已经问题。 – Fogmeister

回答

0

你的问题不是很具描述性/写得很好,但我认为你的问题是你没有缓存你的图像。

试试这个:

let imageCache = NSCache() 
    let cell = tableView.dequeueReusableCell(withIdentifier: "imageLook", for: indexPath) as! imageLookTableViewCell 
    cell.authorLabel.text = self.postsArray[indexPath.row].author 
    cell.likesCountLabel.text = "\(self.postsArray[indexPath.row].likes!)" 
    cell.postID = postsArray[indexPath.row].postId 
    cell.textViewPost.text = self.postsArray[indexPath.row].textPost 
    let url = URL(string: postsArray[indexPath.row].pathToImage as! String) 

    if url != nil { 
     if let cachedImage = imageCache.objectForKey(url) as? UIImage { 
      cell.imagePost.image = cachedImage 
      return 
     } 
     DispatchQueue.global().async { 
      let data = try? Data(contentsOf: url!) 
      DispatchQueue.main.async { 
       if data != nil { 
        if let myImageName = UIImage(data:data!){ 
         imageCache.setObject(myImageName, forKey: url) 
        } 
        cell.imagePost.image = UIImage(data:data!) 
       }else{ 

       } 
      } 
     } 
    } 
    for person in self.postsArray[indexPath.row].peopleWhoLike { 
     if person == FIRAuth.auth()!.currentUser!.uid { 
      cell.likesBtn.isHidden = false 
      break 
     } 
    } 

    return cell 
}