[英]How to save checkMark status for specific UITableViewCell
I have a UITableView
in one UIViewController
, and I try to store the status of the accessoryType so that when the user reload the app, the cells user selected beforehand using NSUserDefault
should display with a checkmark. 我在一个
UIViewController
有一个UITableView
,并且尝试存储附件类型的状态,以便当用户重新加载应用程序时,用户使用NSUserDefault
预先选择的单元格应显示一个选中标记。 But the problem I am facing is that when I check if the cell's data is equal to the data in the user default, some cells that weren't selected are displaying with a checkmark too, but it shouldn't do that. 但是我面临的问题是,当我检查单元格的数据是否与用户默认数据相同时,未选中的某些单元格也会显示一个选中标记,但不应这样做。
here is my codes: 这是我的代码:
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
}
This is likely a cell reuse issue since you're dequeuing cells. 这可能是单元重用的问题,因为您要使单元出队。 You need to make sure to set
cell.accessoryType = .none
for the cases that aren't being set to the checkmark. 对于未设置为选中标记的情况,您需要确保设置
cell.accessoryType = .none
。
try with below snippet. 尝试下面的代码段。
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
}
Save entry.name in user defaults. 将entry.name保存为用户默认设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.