如何在表格单元格中为星级评分?

问题描述

我正在从后端获取totalRaters和totalratings。我将后者除以前者,以确定应该显示多少颗星。始终为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颗星星为止。所有表视图单元格都会发生这种情况。我不确定自己在做什么错。我添加了图像以指示以下问题。 (他们以相反的顺序上传

enter image description here

enter image description here

解决方法

当您上下滚动表时,表视图单元格可能会被重用。您正在阵列中设置图像,但从未清除它们,因此当单元被重用时,它将保留以前使用的任何内容。

您应在表视图单元格类中添加prepareForReuse方法,并清除图像数组。像这样:

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