首页 > 解决方案 > 在tableview单元格中更改like按钮的颜色

问题描述

当用户点击特定帖子的赞按钮时,我试图将我的表格视图单元格中的赞按钮的颜色更改为红色。但是当我为一个帖子点赞时,所有其他帖子的点赞按钮也会变成红色。

 func didTapLike(_ sender: UIButton) {
    if let indexPath = getCurrentCellIndexPath(sender) {
        clickedLike = indexPath
       like()
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    if indexPath.section == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
        
        if let indexPath = clickedLike {
            // change like button to red
            let selectedRow = indexPath.row
            cell.HeartButton.setImage(UIImage(systemName: "heart.fill"), for: .normal)
            cell.HeartButton.tintColor = UIColor.red
            cell.LikeCount.textColor = UIColor.red
            
        }

   }
}

标签: swiftuitableview

解决方案


你必须了解可重复使用细胞的原理。正在发生的事情是你喜欢的细胞被重新使用到你一开始喜欢的细胞。因此,您似乎喜欢一切,因为您从不喜欢的单元格的属性从未重置过它们的属性。

即使您在 cellForRowAt 函数中设置了其属性,稍后也可能会使用相同的属性重用相同的单元格,这就是为什么您可能会看到没有任何更改的原因。因此,您必须在每次重用时专门重置其属性

这可以通过覆盖prepareForReuse()单元格内部并将属性再次设置为其默认值来完成。例如,您可能想在您的PostTableViewCell:

override func prepareForReuse() {
        super.prepareForReuse()
        
        //set it all back to the default values (in this case, heart and black color tint)
        self.HeartButton.setImage(UIImage(systemName: "heart"), for: .normal)
        self.HeartButton.tintColor = UIColor.black
        self.LikeCount.textColor = UIColor.black
        
    }

推荐阅读