我正在尝试使用两张图片 half.png
和 full.png
在 collectionview
上显示用户评分。
但即使我用 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
}
}
Collection View Controller
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! CollectionViewCell
cell.rating = 1.0
return cell
}
最佳答案
由于 UICollectionViewCell 被重用,每次设置评级时,都会向 UIStackView 添加一个新 View 。因此,您应该在添加图像之前重置 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
}
}
}
关于swift - 在 UICollectionViewCell 中实现 UIStackView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51045236/