ios - 如何在表格视图单元格中删除星级?
问题描述
我正在从后端获取 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 颗星星都被填充。这发生在所有表格视图单元格中。我不确定我做错了什么。我添加了图像以指示以下问题。(他们以相反的顺序上传)
解决方案
当您上下滚动表格时,表格视图单元格可能会被重复使用。您正在数组中设置图像,但从不清除它们,因此当重新使用单元格时,它将保留之前使用的所有内容。
您应该向表格视图单元类添加 prepareForReuse 方法并清除图像数组。就像是:
override func prepareForReuse() {
super.prepareForReuse()
arrayStar = [UIImage](count: 5, repeatedValue: UIImage(named: "icon_not_starred"))
}
推荐阅读
- flutter - Flutter Circle 菜单 onPressed 动作
- lua - Lua - 如何按字母顺序对找到的所有文件(通过 LFS)进行排序?
- c# - 在 WinForms 中禁用用户登录按钮
- python - 为什么项目显示在 django 模板/页面的最底部?
- php - PHP | 取日期,将其与当前月份进行比较并将其转换为上个月
- python - 将测量数据集添加到卡尔曼滤波器
- three.js - 带陀螺仪的三个 js 摄像头(设备方向事件)
- redis - Redis 中的会话数据 - 键/值或哈希类型?
- python - 如何在我的蛇应用程序中的网格之间填充颜色
- typescript - TypeScript:使用动态减速器时的根减速器类型