【问题标题】:Change colour of like button in tableview cell在tableview单元格中更改like按钮的颜色
【发布时间】:2021-09-25 13:11:18
【问题描述】:

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

 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
            
        }

   }
}

【问题讨论】:

  • 请不要显示包含未知数的代码。您的工作是提供minimal reproducible example。什么是 clickedLike 以及它是如何设置的?你谈到了一个按钮点击;该点击触发了什么代码,以及如何触发?
  • 我已更新代码以显示 clickedLike 的来源。
  • 细胞被重复使用。在else 的情况下,cell.LikeCount.textColor 和另一个应设置为“默认”。
  • 我这样做了,但没有区别---> if let indexPath = clickedLike { //change like color cell.HeartButton.setImage(UIImage(systemName: "heart.fill"), for: .normal) cell.HeartButton.tintColor = UIColor.red cell.LikeCount.textColor = UIColor.red } else { cell.HeartButton.setImage(UIImage(systemName: "heart"), for: .normal) cell.HeartButton.tintColor = UIColor.black cell.LikeCount.textColor = UIColor.black

标签: swift uitableview


【解决方案1】:

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

即使您在 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
        
    }

【讨论】:

    猜你喜欢
    • 2017-11-02
    • 1970-01-01
    • 2013-03-15
    • 2021-11-14
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 2015-02-24
    相关资源
    最近更新 更多