ios - 当滚动 TableView 内容改变时

标签 ios swift uitableview

我有自定义表格 View 单元格,具有评级星级。我正在使用 https://github.com/hsousa/HCSStarRatingView评级 View 。 有我的表格 View 和单元格 View 代码。

    class RatingTableViewCell: UITableViewCell {

      var value : CGFloat = 0.0
      @IBOutlet weak var starRatingView: HCSStarRatingView!
      @IBOutlet weak var titleLabel: UILabel!
        override func awakeFromNib() {
            super.awakeFromNib()
          initStarRatingView()
          starRatingView.addTarget(self, action: #selector(DidChangeValue(_:)), for: .valueChanged)

        }

        override func setSelected(_ selected: Bool, animated: Bool) {
            super.setSelected(selected, animated: animated)

            // Configure the view for the selected state
        }

      private func initStarRatingView() {
        var scalingTransform : CGAffineTransform!
        scalingTransform = CGAffineTransform(scaleX: -1, y: 1);
        starRatingView.transform = scalingTransform
        starRatingView.emptyStarImage = #imageLiteral(resourceName: "strokStar")
        starRatingView.halfStarImage = #imageLiteral(resourceName: "halfStar")
        starRatingView.filledStarImage = #imageLiteral(resourceName: "fillStar")
        starRatingView.allowsHalfStars = true
      }


      @IBAction func DidChangeValue(_ sender: HCSStarRatingView) {

        self.value = sender.value
      }

class RatingViewController: CustomViewController,UITableViewDelegate,UITableViewDataSource {

  var values : [CGFloat] = [0.5,0.0,0.0,0.0,0.0,0.0,0.0]
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "RatingTableViewCell", for: indexPath) as! RatingTableViewCell

    values[indexPath.row] = cell.value
    cell.starRatingView.value = values[indexPath.row]
    return cell
  }
//MARK: _Table data source

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    values.count
  }

}

滚动表格 View 时出现问题。 dequeue Reusable Cell 数据错误。如何更新每个单元格的值数据?

最佳答案

问题是您将值存储在单元格中。看看这两行:

let cell = tableView.dequeueReusableCell(withIdentifier: "RatingTableViewCell", for: indexPath) as! RatingTableViewCell
values[indexPath.row] = cell.value

您将一个单元格出列并将其值分配给 values[indexPath.row]。您在滚动时注意到的问题是由于重复使用的单元格以前用于不同的 indexPath,这意味着它们的值(您分配给 values[indexPath.row])是用于其先前的 indexPath。

要解决这个问题,我建议去掉 RatingTableViewCell 中的值变量。相反,定义一个协议(protocol) RatingTableViewCellDelegate 将用于通知 RatingViewController 有关新值的信息。

关于ios - 当滚动 TableView 内容改变时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46756147/

相关文章:

objective-c - 创建 IBOutlet 还是 UIView?

iOS 重大变更频率

ios - Xcode 10.1 无法调用 'copyBytes'

php - 使用 Firebase 和 PHP 在 iOS 中推送通知

ios - 如何实现数据表

ios - iOS-tableView,按降序对JSON数组排序

ios - View Controller 背景和状态栏背景的单独颜色

ios - 删除应用程序不会删除应用程序组数据

swift - Swift 中常见的父 View

ios - UITableView中的UIDatePicker,保证Visibility