我在一个UIViewController中有一个UITableView,我尝试存储accessoryType的状态,以便当用户重新加载应用程序时,用户预先使用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
}发布于 2017-11-08 07:29:12
这可能是一个信元重用问题,因为您正在将信元出队。您需要确保为未设置为复选标记的情况设置cell.accessoryType = .none。
发布于 2017-11-08 13:53:43
尝试使用下面的代码片段。
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保存为用户默认值。
https://stackoverflow.com/questions/47168831
复制相似问题