ios - 基于 UITableview 单元格选择和取消选择,快速添加和删除项目到数组中

标签 ios swift uitableview

就我而言,我在 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/

相关文章:

iphone - Objective-C 语法 : addTarget on UISwipeGestureRecognizer

swift - 为 shell 命令获取实用程序的完整路径,如 7zip 等

ios - 快速/对快照执行多个操作

ios - 滚动前第一部分第一行的 tableview 行高错误

ios - Tableview [cell.contentview viewwithtag :] is returning nil

swift - 如何给 UITableView 动态高度

ios - 从子类更改主类

ios - canOpenURL 成功但 openURL 失败,对于 tel 作为 urlschema

ios - iPhone X 和底部安全区域插图

ios - Tableview 在选择上传递相同的数据