如何解决在表格视图中滚动后,选中标记会发生变化
无论我做什么,滚动后都无法保持选中标记项目。我知道这与以下事实有关:当可见项目时,单元将被重用,但我不确定如何处理。
以下代码成功显示了第一次加载时选择的正确项目,问题是,一旦我开始滚动,它就会随机选择其他项目。
滚动后保留所选项目并防止选择不需要的项目/行的正确方法是什么?
class CategoriesViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var categories: Results<Category>! // I'm getting this from the Realm data base
var categoryTracker:Category? // I'm getting this from other view controler
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
return categories.count
}
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "categoriesCell",for: indexPath) as! CategoriesCell
let categoryList = categories[indexPath.row]
cell.labelCategoryName.text = categoryList.categoryName
if categories[indexPath.row].categoryID == self.categoryTracker!.categoryID{
cell.accessoryType = .checkmark
}
return cell
}
func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
// show checkmark on category for selected item and uncheck the rest
for row in 0..<tableView.numberOfRows(inSection: indexPath.section) {
if let cell = tableView.cellForRow(at: IndexPath(row: row,section: indexPath.section)) {
cell.accessoryType = row == indexPath.row ? .checkmark : .none
}
}
}
}
图片:
解决方法
您是对的。发生这种情况是因为当带有.checkmark的单元被重用时,它不会将其附件类型重置为.none
您应该更新您的:
if categories[indexPath.row].categoryID == self.categoryTracker!.categoryID{
cell.accessoryType = .checkmark
}
收件人:
if categories[indexPath.row].categoryID == self.categoryTracker!.categoryID {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。