当单元格被重用时,我在 TableViewCell 中的心脏按钮状态被保存

My heart button state in TableViewCell is saved when the cell gets reused

我正在使用 xib 填充 table 视图。每个单元格都有一个带有心脏图像的按钮,可以填充或不填充。选择按钮后,它会将按钮所在的行添加到收藏夹视图中。到目前为止它的工作。问题是,当我滚动 table 视图时,被重复使用的单元格显示为充满心形而不是空心。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   if indexPath.row % 2 == 0 {
       let cellIdentifier = "cell"
       let cell = productTableView.dequeueReusableCell(withIdentifier: cellIdentifier ,for :indexPath)
           as! ProductsTableViewCell
       let model = productArray[indexPath.row]
       cell.favouriteButton.tag = indexPath.row
       cell.configureCell(model)

       return cell
   }else {
       let cellIdentifier = "cell2"
       let cell = productTableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! Product2TableViewCell
       let model = productArray[indexPath.row]
       cell.favouriteButton.tag = indexPath.row

       if favouriteProductsArray.count != 0 {
           for fave in favouriteProductsArray {
               if fave.product_id == model.id{
                   cell.favouriteButton.isSelected = true
               }
           }
       }else{
           cell.favouriteButton.isSelected = false
       cell.setupCell(model)
       return cell
   }
}

我认为问题出在以下代码上:

if favouriteProductsArray.count != 0 {
    for fave in favouriteProductsArray {
        if fave.product_id == model.id{
            cell.favouriteButton.isSelected = true
        }
    }
}else{
    cell.favouriteButton.isSelected = false
}

在第一个 if 语句中,您没有逻辑将 isSelected 设置为 false。我会按如下方式重做该代码:

var selected = false
if favouriteProductsArray.count != 0 {
    for fave in favouriteProductsArray {
        if fave.product_id == model.id {
            selected = true
            break
        }
    }
}
cell.favouriteButton.isSelected = selected

这确保 isSelected 设置为 false,除非您找到匹配的 ID。

我遇到了类似的问题。我所做的是有一个数组来跟踪 .isSelected 值,并在 dequeuereusablecell 之后根据数组中的值设置 isSelected。这可能只是一个 if 语句。

所以这将是一个包含 n 个元素的数组,其中 n 是您要加载的食品数量。每个元素将是 true 或 false,这是 isSelected 的相应值,它是在 dequeuereusablecell 之后设置的。

虽然您在 else 部分正确设置了收藏夹按钮,但当 if-condition 为真时,您没有这样做。也在那里做。或者更好的是,提取代码以在 if 语句之外执行此操作。