UITableViewCell在重用后加载不正确的图像

时间:2017-10-17 18:24:39

标签: ios swift uitableview

我有一个tableview,用来自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()



    }

}

Tableview Cell

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)"
    }
}

的TableView

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()
    }

1 个答案:

答案 0 :(得分:0)

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

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

相关问题