2017-06-18 36 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 
} 
相關問題