我正在尝试使用两个图像collectionview
和half.png
在full.png
上显示用户评分,如下所示。
但是,尽管我用1 star
进行了硬编码以进行测试,但有时在滚动过程中它显示的内容多于1 star
。它一直在增加。
我想知道如何处理这个问题?
CollectionViewCell
import UIKit
class CollectionCell: UICollectionViewCell {
@IBOutlet var ratingView: UIStackView!
var rating : Float!
{
didSet {
self.ratingView.addArrangedSubview(addRating())
}
}
func addRating() -> UIStackView
{
let stackView = UIStackView()
stackView.axis = .horizontal
let oneStarImage = UIImage(named: "full_star")
let halfStarImage = UIImage(named: "half_star")
//hard coded
var value = 1.0
while true {
value -= 1
if value >= 0 {
print("Add 1 star")
let imageView = UIImageView()
imageView.image = oneStarImage
stackView.addArrangedSubview(imageView)
} else if value == -0.5 {
print("Add half a star")
let imageView = UIImageView()
imageView.image = halfStarImage
stackView.addArrangedSubview(imageView)
break
}
else {
break
}
}
return stackView
}
}
CollectionViewController
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! CollectionViewCell
cell.rating = 1.0
return cell
}
答案 0 :(得分:2)
随着UICollectionViewCell被重用,每次您设置等级时,都会向UIStackView添加一个新视图。因此,您应该在添加图像之前重置UIStackView。另外,每次添加评分时可能都不必创建UIStackView。您可以改为重用ratingView。因此,完整的代码应为:
var rating : Float!
{
didSet {
self.addRating()
}
}
func addRating()
{
// Empty the ratingView first
ratingView.arrangedSubviews.forEach { $0.removeFromSuperview() }
let oneStarImage = UIImage(named: "full_star")
let halfStarImage = UIImage(named: "half_star")
//hard coded
var value = 1.0
while true {
value -= 1
if value >= 0 {
print("Add 1 star")
let imageView = UIImageView()
imageView.image = oneStarImage
ratingView.addArrangedSubview(imageView)
} else if value == -0.5 {
print("Add half a star")
let imageView = UIImageView()
imageView.image = halfStarImage
ratingView.addArrangedSubview(imageView)
break
}
else {
break
}
}
}
答案 1 :(得分:2)
您还可以将其用于重用的UICollectionViewCell或UITableViewCell
override func prepareForReuse() {
super.prepareForReuse()
self.ratingView = UIStackView()
}
覆盖函数以准备要重用的单元格。但是,您应该重新初始化在单元格中分配值的组件。