就我而言,我在 codable
的帮助下将 JSON
数据加载到 Tableview
中。表格 View 有多个选择
和取消选择
复选标记选项可用。现在,我需要将选定的值插入到一个数组中,同时如果用户取消选择单元格,则需要从同一数组中删除相关值。存储的数组数据,我将在多个 View Controller 中使用。如何实现这一目标?
JSON 可编码
// MARK: - Welcome
struct Root: Codable {
let status: Bool
let data: [Datum]
}
// MARK: - Datum
struct Datum: Codable {
let userid, firstname, designation: String?
let profileimage: String?
}
我的 Tableview 委托(delegate)代码库
var studentsData = [Datum]()
var sessionData = [Datum]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.studentsData.count
}
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
if let index = sessionData.index(of:item) {
sessionData.remove(at: index)
}
print(sessionData)
} else {
cell.accessoryType = .checkmark
// Checkmark selected data Insert into array
self.sessionData.append(item)
print(sessionData)
}
}
}
最佳答案
您可以通过搜索索引来删除数组中的项目
let index = try? array.firstIndex(where: { $0. userid == sessionData[indexPath.row].userid })
或者你可以使用这个Checking if an array of custom objects contain a specific custom object
关于ios - 基于 UITableview 单元格选择和取消选择,快速添加和删除项目到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58669519/