ios - 防止重复使用的单元格中的按钮再次出现
问题描述
@objc func addinterestserver(_ sender: UIButton) {
sender.backgroundColor = UIColor.white
sender.setTitleColor(UIColor.black, for: .normal)
sender.setTitle(NSLocalizedString("Added", comment: ""), for: .normal)
sender.isEnabled = false
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SearchInterestsCustom
let release = arrayOfRels[(indexPath as NSIndexPath).row]
cell.user.text = release.title
cell.match.text = release.count + NSLocalizedString(" people added", comment: "")
cell.addbutton.tag = release.eventID
cell.addbutton.addTarget(self, action: #selector(SearchInterests.addinterestserver), for: .touchUpInside)
cell.addbutton.layer.cornerRadius = 20
return cell
}
用户点击按钮后,它也会影响其他单元格的按钮,显然我在滚动时多次看到相同的修改按钮。
如何避免这种情况?
解决方案
您可以通过以下方式避免这种情况
var allSelected = [Int]()
//
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SearchInterestsCustom
if allSelected.contains(release.eventID) {
cell.addbutton.backgroundColor = UIColor.white
cell.addbutton.setTitleColor(UIColor.black, for: .normal)
cell.addbutton.setTitle(NSLocalizedString("Added", comment: ""), for: .normal)
cell.addbutton.isEnabled = false
}
else {
// set default values
}
}
//
@objc func addinterestserver(_ sender: UIButton) {
sender.backgroundColor = UIColor.white
sender.setTitleColor(UIColor.black, for: .normal)
sender.setTitle(NSLocalizedString("Added", comment: ""), for: .normal)
sender.isEnabled = false
allSelected.append(sender.tag) // store it here
}
推荐阅读
- javascript - useState 没有更新 - nextjs
- python - 用阶乘替换列表中 3 的倍数的偶数
- amazon-web-services - 使用 pre-commit 钩子获取“E0000 模板需要是一个对象”。
- discord.js - discord.js 锁定命令引发错误,无法读取未定义的“拒绝”
- title - 如何使用 Altair 在多个图表上移动/对齐 X 轴标题?
- python - 省略第一个单词并删除属于另一个单词的单词
- php - 从 php 中的二维数组中查找缺失值并插入缺失的元素
- c# - 我该如何处理“'Program.D(int)':并非所有代码路径都返回一个值”
- ios - 从 Swift 二进制文件中删除文件名
- c# - 如果绑定属性具有特定值,如何用圆圈覆盖单元格的内容?