ios - 重新启动视图控制器后,Swift Tableview 复选标记消失了
问题描述
就我而言,我正在将JSON
数据加载到tableview
. 在这里,tableview cell 实现了多个单元格的选择checkmark
和uncheckmark
选项。如果 go previousviewcontroller
并再次返回 tableview 控制器,则最后选择的复选标记消失。怎么store
办?
JSON 可编码
// MARK: - Welcome
struct Root: Codable {
let status: Bool
let data: [Datum]
}
// MARK: - Datum
struct Datum: Codable, Hashable {
let userid, firstname, designation: String?
let profileimage: String?
}
自定义单元类
class MyCustomCell: UITableViewCell {
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var nameCellLabel: UILabel!
@IBOutlet weak var subtitleCellLabel: UILabel!
}
Tableview 复选标记的代码
var studentsData = [Datum]()
var sessionData = Set<Datum>()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:MyCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! MyCustomCell
let item = self.studentsData[indexPath.row]
cell.nameCellLabel.text = item.firstname
cell.subtitleCellLabel.text = item.designation
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let item = self.studentsData[indexPath.row]
if let cell = tableView.cellForRow(at: indexPath) {
if cell.accessoryType == .checkmark {
cell.accessoryType = .none
// UnCheckmark cell JSON data Remove from array
self.sessionData.remove(item)
print(sessionData)
} else {
cell.accessoryType = .checkmark
// Checkmark selected data Insert into array
self.sessionData.insert(item)
print(sessionData)
}
}
}
解决方案
您应该始终将 checkMark 状态保存在另一个数组或变量中。如果只能选择一项:
var SELECTED_ITEMS= [YOUR_DATA_TYPE]()//It must be global within tableViewController
如果允许多选
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let item = self.studentsData[indexPath.row]
if SELECTED_ITEMS.contain(item){
SELECTED_ITEMS.remove(item)
}else{
SELECTED_ITEMS.append(item)
}
}
请记住 SELECTED_ITEM 应该是您的 tableviewdata 的数组,而 SELECTED_ITEM 只是您的 tableview 数据的同一类型。此外,如果您在 Tableview 控制器中的 ViewDidLoad 或 ViewWillAppear 中初始化模型,则当 tableview 出现时,make 应该SELECTED_ITEMS
并且SELECTED_ITEM
不会被重置。
然后
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
........
cell.accessoryView = SELECTED_ITEMS.contain(item) ? .checkmark:.none// Multi Selection
.........
}
通常,您更新您的模型、变量或数组或任何适合您的代码的内容,以跟踪选择/未选择的索引路径。然后在 cellForRowAt 你可以检查上面的变量/数组...来设置附件。
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath){}
也将工作
推荐阅读
- java - 导致死锁的代码与阻止死锁的代码有什么区别?代码示例需要说明
- feedly - 需要 Feedly API 帮助
- asynchronous - Vue.js - 更新异步计算属性后更新计算属性
- sql - 如何在 HSQLDB GUI 中执行多个命令?
- swift - NSSavePanel 名称不是用户可编辑的
- html - 我可以单循环浏览一个 HTML 程序吗?我想找出每条消息的来源
- jenkins - Jenkins 无法随机运行定期/计划的作业 - “错误持久化 EventHistoryStore 条目文件”
- excel - 在 Excel 中计数到某个数字时查找值
- java - 计算二维数组中两个值之间的最大欧几里得距离
- sql - 基于链接三个表中的数据更新项目