我正在使用 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
}
}
最佳答案
我认为问题在于以下代码:
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/