在 UICollectionViewCell 中实现 UIStackView

Implementing UIStackView inside UICollectionViewCell

我正在尝试使用两张图片 half.pngfull.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
   }
 }

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
}

由于重用了UICollectionViewCell,每次设置评分时,都会向UIStackView 添加一个新视图。因此,您应该在添加图像之前重置 UIStackView。此外,可能没有必要在每次添加评级时都创建一个 UIStackView。您可以改用 ratingView。所以,完整的代码应该是:

var rating : Float!
{
    didSet {
        self.addRating()
    }
}

func addRating()
{
    // Empty the ratingView first
    ratingView.arrangedSubviews.forEach { [=10=].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
        }
    }
}

您还可以使用重用的 UICollectionViewCell 或 UITableViewCell,

override func prepareForReuse() {
    super.prepareForReuse()
    self.ratingView = UIStackView()
}

覆盖 func 以准备要重用的单元格。但是,您应该重新初始化您在单元格中分配值的组件。