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

标签 ios swift uitableview

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

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
   }
}

enter image description here

最佳答案

我认为问题在于以下代码:

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。

关于ios - 当单元格被重用时,我在 TableViewCell 中的心脏按钮状态被保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43031553/

相关文章:

ios - 从扬声器获取音频样本

ios - 在 iOS 上使用 VoiceOver 时如何获取当前聚焦的元素?

ios - 如何检测用户是否点击警报打开应用程序?

cocoa-touch - 由于未命中 RLMRealm.setSchemaVersion block ,无法迁移到具有更新属性的新模式

ios - 如何指定在 UITableView 中显示哪些单元格?

ios - 尝试播放某些轨道时出现 cocoalibspotify 错误

ios - 用AVAudioPlayer改变音高的简单方法吗?

ios - 如何更改导航栏中 titleView 的大小。因为在 navigationBar 的 titleView 和 backButton 之间有一个空隙

ios - 当我滚动 tableview 时,如何使 headerView 与 UItableViewCell 一起滚动(不停留在 tableview 的顶部)

ios - 如何将表输出传递到另一个 View Controller ?