0

我有一个UITableViewin one UIViewController,我尝试存储附件类型的状态,以便当用户重新加载应用程序时,用户预先选择使用的单元格NSUserDefault应该显示一个复选标记。但我面临的问题是,当我检查单元格的数据是否等于用户默认值中的数据时,一些未选中的单元格也会显示一个复选标记,但它不应该那样做。

这是我的代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = newCategoriesTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.backgroundColor = colorArray[indexPath.row]
    let entry: Categories
    if isFiltering() {
        entry = filteredCategories[indexPath.row]
    } else {
        entry = categoryTitles[indexPath.row]
    }

    cell.selectionStyle = .none

    cell.textLabel?.text = entry.name
    cell.detailTextLabel?.text = entry.description

    let defaults = UserDefaults.standard
    if let userCategortList = defaults.object(forKey: "userCategoryList") as? [String]{
            for category in userCategortList{
                if(cell.textLabel?.text == category){
                    cell.accessoryType = .checkmark
                    break
                }
            }
        }

    return cell
}
4

2 回答 2

0

这可能是一个单元重用问题,因为您正在使单元出列。您需要确保为cell.accessoryType = .none未设置为复选标记的情况进行设置。

于 2017-11-07T23:29:11.510 回答
0

尝试以下代码段。

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = newCategoriesTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            cell.backgroundColor = colorArray[indexPath.row]
            let entry: Categories
            if isFiltering() {
                entry = filteredCategories[indexPath.row]
            } else {
                entry = categoryTitles[indexPath.row]
            }

            cell.selectionStyle = .none

            cell.textLabel?.text = entry.name
            cell.detailTextLabel?.text = entry.description

            let defaults = UserDefaults.standard
            if let entry.name ==  (defaults.object(forKey: "userCategoryList") as? [String]){
                  cell.accessoryType = .checkmark                    
                }
            else{
                  cell.accessoryType = .none
                }

            return cell
        }

将 entry.name 保存在用户默认值中。

于 2017-11-08T05:53:43.140 回答