首页 > 解决方案 > 如何在表格视图单元格中删除星级?

问题描述

我正在从后端获取 totalRaters 和 totalRatings。我将后者除以前者以确定我应该展示多少颗星。它始终是 0 到 5 之间的数字,包括 0 和 5。

我在 UITableViewCell 子类中的星级代码是:

fileprivate let starStack : UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.alignment = .fill
        stackView.distribution = .fillEqually
        stackView.spacing = 4
        return stackView
    }()

func setupStar() {
        //... code to add a label
        backgroundView.addSubview(starStack)
        starStack.translatesAutoresizingMaskIntoConstraints = false
        starStack.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 8).isActive = true
        starStack.leadingAnchor.constraint(equalTo: backgroundView.leadingAnchor, constant: 8).isActive = true
        starStack.bottomAnchor.constraint(equalTo: backgroundView.bottomAnchor, constant: -8).isActive = true
        starStack.heightAnchor.constraint(equalToConstant: 34).isActive = true
}

func setValues(totalRatings Int, totalRaters Int) {
        let ratings = totalRatings / totalRaters
        if ratings > 0 {
            for index in 0...ratings - 1 {
                arrayStar[index].image = UIImage(named: "icon_starred")
            }
        }
}

问题是,每当我向下滚动(即单元格在视口下方消失)然后再向上滚动时,星星就会不断增加,直到所有 5 颗星星都被填充。这发生在所有表格视图单元格中。我不确定我做错了什么。我添加了图像以指示以下问题。(他们以相反的顺序上传)

在此处输入图像描述在此处输入图像描述

标签: iosswift

解决方案


当您上下滚动表格时,表格视图单元格可能会被重复使用。您正在数组中设置图像,但从不清除它们,因此当重新使用单元格时,它将保留之前使用的所有内容。

您应该向表格视图单元类添加 prepareForReuse 方法并清除图像数组。就像是:

override func prepareForReuse() {
    super.prepareForReuse()
    arrayStar = [UIImage](count: 5, repeatedValue: UIImage(named: "icon_not_starred"))
}

推荐阅读