ios – Swift图像在异步图像加载到UITableViewCell后滚动时更改为错误的图像

前端之家收集整理的这篇文章主要介绍了ios – Swift图像在异步图像加载到UITableViewCell后滚动时更改为错误的图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试在FriendsTableView(UITableView)单元格中异步加载图片.图像加载正常,但是当我滚动表格时,图像会改变几次,错误的图像会被分配给错误的单元格.

我已经尝试了我在StackOverflow中可以找到的所有方法,包括向raw添加标签然后检查它但是没有用.我还要验证应该使用indexPath更新的单元格并检查单元格是否存在.所以我不知道为什么会这样.

这是我的代码

  1. func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  2. let cell = tableView.dequeueReusableCellWithIdentifier("friendCell",forIndexPath: indexPath) as! FriendTableViewCell
  3. var avatar_url: NSURL
  4. let friend = sortedFriends[indexPath.row]
  5.  
  6. //Style the cell image to be round
  7. cell.friendAvatar.layer.cornerRadius = 36
  8. cell.friendAvatar.layer.masksToBounds = true
  9.  
  10. //Load friend photo asyncronisly
  11. avatar_url = NSURL(string: String(friend["friend_photo_url"]))!
  12. if avatar_url != "" {
  13. getDataFromUrl(avatar_url) { (data,response,error) in
  14. dispatch_async(dispatch_get_main_queue()) { () -> Void in
  15. guard let data = data where error == nil else { return }
  16. let thisCell = tableView.cellForRowAtIndexPath(indexPath)
  17. if (thisCell) != nil {
  18. let updateCell = thisCell as! FriendTableViewCell
  19. updateCell.friendAvatar.image = UIImage(data: data)
  20. }
  21. }
  22. }
  23. }
  24. cell.friendNameLabel.text = friend["friend_name"].string
  25. cell.friendHealthPoints.text = String(friend["friend_health_points"])
  26. return cell
  27. }

解决方法

这是因为UITableView重用了单元格.以这种方式加载它们会导致异步请求在不同时间返回并弄乱订单.

我建议你使用一些图书馆,让你的生活更轻松如翠鸟.它将为您下载和缓存图像.您也不必担心异步调用.

https://github.com/onevcat/Kingfisher

你的代码看起来像这样:

  1. func tableView(tableView: UITableView,forIndexPath: indexPath) as! FriendTableViewCell
  2. var avatar_url: NSURL
  3. let friend = sortedFriends[indexPath.row]
  4.  
  5. //Style the cell image to be round
  6. cell.friendAvatar.layer.cornerRadius = 36
  7. cell.friendAvatar.layer.masksToBounds = true
  8.  
  9. //Load friend photo asyncronisly
  10. avatar_url = NSURL(string: String(friend["friend_photo_url"]))!
  11. if avatar_url != "" {
  12. cell.friendAvatar.kf_setImageWithURL(avatar_url)
  13. }
  14. cell.friendNameLabel.text = friend["friend_name"].string
  15. cell.friendHealthPoints.text = String(friend["friend_health_points"])
  16. return cell
  17. }

猜你在找的iOS相关文章