Ios 在“表视图”中滚动后,选中标记会发生更改

Ios 在“表视图”中滚动后,选中标记会发生更改,ios,swift,uitableview,Ios,Swift,Uitableview,无论我做什么,我都无法在滚动后保持选中复选标记项。我知道这与这样一个事实有关,即当项目可见时,单元格会被重用,但我不确定如何处理这个问题 下面的代码成功地显示了在第一次加载时选择的正确项目,问题是一旦我开始滚动,它就会继续随机选择其他项目 滚动后保留所选项目并防止选择不需要的项目/行的正确方法是什么 class CategoriesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

无论我做什么,我都无法在滚动后保持选中复选标记项。我知道这与这样一个事实有关,即当项目可见时,单元格会被重用,但我不确定如何处理这个问题

下面的代码成功地显示了在第一次加载时选择的正确项目,问题是一旦我开始滚动,它就会继续随机选择其他项目

滚动后保留所选项目并防止选择不需要的项目/行的正确方法是什么

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
            }
        }
    }
}
class CategoriesViewController:UIViewController、UITableViewDelegate、UITableViewDataSource{
var categories:Results!//我是从领域数据库中获取的
var categoryTracker:Category?//我是从另一个视图控件获取此信息的
func tableView(tableView:UITableView,numberofrowsinssection:Int)->Int{
返回类别。计数
}
func tableView(tableView:UITableView,cellForRowAt indexath:indexPath)->UITableViewCell{
将cell=tableView.dequeueReusableCell(标识符为:“categoriesCell”,for:indexath)设为!categoriesCell
让categoryList=categories[indexPath.row]
cell.labelCategoryName.text=categoryList.categoryName
如果类别[indexPath.row].categoryID==self.categoryTracker!.categoryID{
cell.accessoryType=.checkmark
}
返回单元
}
func tableView(tableView:UITableView,didSelectRowAt indexPath:indexPath){
//在所选项目的类别上显示复选标记,并取消选中其余项目

对于0..中的行,您是对的。这是因为当使用带有.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
}