【问题标题】:UITableViewCell loading incorrect image after reuseUITableViewCell重用后加载不正确的图像
【发布时间】:2017-10-17 18:24:38
【问题描述】:

我有一个表格视图,它使用来自 firebase 的数据填充其单元格。每个单元格拥有一个图像,每个图像被异步加载和缓存。 问题是随机单元格将使用错误的图像,尽管单元格中的其他数据是正确的。如果我滚动以使单元格消失,则会加载正确的图像。

研究

Images in UITableViewCells are loading wrong(不太懂Obj C)

What is the correct way to use prepareForReuse?

图像缓存:

import Foundation
import UIKit

let imageCache = NSCache<NSString, AnyObject>()

extension UIImageView {

    func loadImageUsingCache(urlString: String) {
        self.image = #imageLiteral(resourceName: "logo3")

        if let cachedImage = imageCache.object(forKey: urlString as NSString) as? UIImage {
            self.image = cachedImage
            return
        }

        let url = URL(string: urlString)
        URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
            if error != nil {
                print(error!)
                return
            }

            DispatchQueue.main.async(execute: {
                if let downloadedImage = UIImage(data: data!) {

                    imageCache.setObject(downloadedImage, forKey: urlString as NSString)
                    self.image = downloadedImage
                }
            })

        }).resume()



    }

}

表格视图单元格

import Foundation
import Firebase

class GroupCell: UITableViewCell {

    var group: Groups!
    var members = [String]()


    @IBOutlet weak var groupImage: UIImageView!
    @IBOutlet weak var groupName: UILabel!
    @IBOutlet weak var groupRep: UILabel!
    @IBOutlet weak var memberCount: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()

    }


    func configureCell(group: Groups) {
        self.group = group

        self.groupName.text = group.name
        self.groupRep.text = "\(group.groupScore)"

        if let groupImage = group.groupImage {
            self.groupImage.loadImageUsingCache(urlString: groupImage)

        } else {
            self.groupImage.image = //random image
        }

        for member in group.members {
            self.members.append(member.key)

        }
         self.memberCount.text = "\(members.count)"
    }
}

表格视图

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell") as? GroupCell {
            let group = FriendSystem.system.activeGroups[indexPath.row]
            cell.configureCell(group: group)

            return cell
        }

        return UITableViewCell()
    }

【问题讨论】:

标签: ios swift uitableview


【解决方案1】:

听起来您需要将 prepareForReuse 方法添加到您的 GroupCell 类中。

在该方法中添加self.groupImage.image = nil 它会将您的图像视图重置为空,直到设置正确的图像。

【讨论】:

  • 我之前实际上已经实现了这段代码,但没有成功。这是我提到的线程之一
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多