【发布时间】: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