gpt4 book ai didi

swift - 在 UICollectionViewCell 中实现 UIStackView

转载 作者:搜寻专家 更新时间:2023-11-01 06:13:02 24 4
gpt4 key购买 nike

我正在尝试使用两张图片 half.pngfull.pngcollectionview 上显示用户评分。

但即使我用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com