我在一个UITableView
中有UIViewController
,我尝试存储accessoryType的状态,以便当用户重新加载应用时,预先使用NSUserDefault
选择的单元格应该带有复选标记的显示。但我面临的问题是,当我检查单元格的数据是否等于用户默认值中的数据时,一些未被选中的单元格也会显示复选标记,但它不应该&#39这样做。
这是我的代码:
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
}
答案 0 :(得分:0)
这可能是一个单元重用问题,因为您要将单元格出列。您需要确保为未设置为复选标记的案例设置cell.accessoryType = .none
。
答案 1 :(得分: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。