swift - 在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
}
}
}
解决方案
你必须了解可重复使用细胞的原理。正在发生的事情是你喜欢的细胞被重新使用到你一开始不喜欢的细胞。因此,您似乎喜欢一切,因为您从不喜欢的单元格的属性从未重置过它们的属性。
即使您在 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
}
推荐阅读
- php - URL 变量中的特殊字符
- javascript - 保存画布元素
- python - 如何根据 GroupBy 条件从另一个数据框创建数据框
- amazon-web-services - 将 AWS S3 存储桶访问限制为单个角色
- azure - 具有可编辑文件夹的 .net core azure 管道部署
- react-native - 如何发布和保持安装的 React Native 应用程序的多个版本?
- c - 为什么 gcc 在汇编中使用函数指针的相对地址?
- android - 开发控制台与火基地崩溃报告有什么区别
- python - 使用 pandas DataFrame 的 Mysql 更新表
- c++ - C++:将数据保存在并行数组中